从C#TCP服务器到Android设备的图像传输
我成功地使用从C#到Java(Android)的TCP套接字进行连接。我可以发送和接收字符串消息没有问题。但是,当我尝试接收从C#服务器发送的PNG图像时,我在Android Activity View上只显示黑屏。从C#TCP服务器到Android设备的图像传输
基本上,服务器侦听并等待,直到客户端发送消息。当服务器收到消息时,它将响应向客户端发送图像。
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();
}
Android客户端:
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活动?我在这里错过了什么?
首先。 TCP不发送消息,它发送字节流。一个字节流,您可以包含从消息的一小部分到几个消息的任何内容。不要以为你会收到一封邮件,其中一封是Receive()
。
如果您在服务器中有适当的错误处理,您将会注意到。不要忽略异常或断开连接。处理它们。
解决您的问题最简单的方法是发送一个整数头,告诉长度。阅读该标题,然后继续致电Read
,直到整个图像传输完毕。
为什么你的字符串工作的原因是该消息很小,而且你之后没有直接传输任何东西。因此给你发送消息的错觉。 (尝试直接发送两条消息,Nagle algorithm应该将它们打包在一起,以便在相同的Read()
中收到它们)。
是的,你是对的。我试图发送更小的图像和繁荣 - 成功。所以发送任何大小的图像,我按照你的建议做了,做了一个与里面读一个循环。然而,为了将图像长度作为一个整数对我来说是相当麻烦的,我最终将它转换为UTF8 String,然后转换为byte [](因为AFAIK c#只发送byte []),然后再次转换两次Java。那么只要它有效:> – jigglypuff
但你为什么不与Web服务的尝试,并很容易地获取这个 –
是工作的罚款与me.try这个 http://*.com/questions/16498370/receiving-multi-images-over-tcp – waqasanwaar