【发布时间】:2011-12-06 21:00:06
【问题描述】:
我已经成功地使用 TCP 套接字从 C# 到 Java (Android) 建立了连接。我可以发送和接收字符串消息没有问题。但是,当我尝试接收从 C# 服务器发送的 PNG 图像时,我在 Android Activity View 上只看到黑屏。
基本上,服务器会监听并等待客户端发送消息。服务端收到消息后,会发送图片给客户端。
C# 服务器:
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received. Now let's send an image.
byte[] pic = new byte[5000*1024];
pic = ImageConverter.imageToByteArray(System.Drawing.Image.FromFile("C:\\ic_launcher.png"));
clientStream.Write(pic, 0, pic.Length);
clientStream.Flush();
}
安卓客户端:
Socket s = new Socket("192.168.1.154", 8888);
DataInputStream ins = new DataInputStream(s.getInputStream());
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//Let's send output message
String outMsg = "TCP connecting to " + 8888 + System.getProperty("line.separator");
out.write(outMsg);
out.flush();
//Receive the image from server.
int bytesRead;
byte[] pic = new byte[5000*1024];
bytesRead = ins.read(pic, 0, pic.length);
//Decode the byte array to bitmap and set it on Android ImageView
Bitmap bitmapimage = BitmapFactory.decodeByteArray(pic, 0, bytesRead);
ImageView image = (ImageView) findViewById(R.id.test_image);
image.setImageBitmap(bitmapimage);
//Show in android TextView how much data in bytes has been received (for debugging)
String received;
received= Integer.toString(bytesRead);
test.setText(received);
//close connection
s.close();
现在收到的变量显示已经传输了约 3000 字节,而图像大小实际上是 4.147 字节(显示在 Windows 资源管理器中),这听起来不对。
那么,为什么图像没有显示在 Android Activity 中?我在这里错过了什么?
【问题讨论】:
-
但是为什么你不尝试使用网络服务并轻松获取
-
这对我很好。试试这个stackoverflow.com/questions/16498370/…
标签: c# java android sockets tcp