如何连续从C#套接字上的android接收位图?

时间:2018-10-22 12:02:30

标签: c# android sockets visual-studio-2013

我正在使用自己的远程管理工具,由于该服务器端的接收器功能发生错误,该项目已停止。

  

算术运算导致溢出。 (添加整数)

在此行:

var imageData = new byte[length];

enter image description here

void server_Received(Listener l, Info i, string received) {

    string[] cmd = received.Split('|');

    switch (cmd[1])
    {

        case "PRINT":

            //MessageBox.Show("print");

            Thread threadPrint;

            threadPrint = new Thread(() =>
            {
                var lengthData = new byte[4];
                var lengthBytesRead = 0;

                while (lengthBytesRead < lengthData.Length)
                {
                    var read = i.sock.Receive(lengthData, lengthBytesRead, lengthData.Length - lengthBytesRead, SocketFlags.None);
                    if (read == 0) return;
                    lengthBytesRead += read;
                }
                var length = BitConverter.ToInt32(lengthData, 0);
                var imageData = new byte[length];
                var imageBytesRead = 0;

                while (imageBytesRead < imageData.Length)
                {
                    var read = i.sock.Receive(imageData, imageBytesRead, imageData.Length - imageBytesRead, SocketFlags.None);
                    if (read == 0) return;
                    imageBytesRead += read;
                }

                using (var stream = new MemoryStream(imageData))
                {
                    var bitmap = new Bitmap(stream);
                    Invoke(new ImageCompleteDelegate(ImageComplete), new object[] { bitmap });
                }

            });

            threadPrint.Start();

            break;
    }
}

我从this参考中获得的接收方代码(请参阅客户代码),并且已按照我的需要进行了调整,如您在上面看到的那样。

这是我在android(Java)上发送位图的方式:

try {
                dos = new DataOutputStream(SocketBackgroundService.xclientSocket.getOutputStream());
                PrintWriter out = new PrintWriter(
                        new BufferedWriter(
                                new OutputStreamWriter(dos)
                        )
                );
                out.println("|PRINT|");
                out.flush();
                dos.writeInt(array.length);
                dos.write(array, 0, array.length);
                dos.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }

然后,我想知道可以采取什么措施来解决此问题?

谢谢。

1 个答案:

答案 0 :(得分:2)

解决方案是插入:

Array.Reverse(lengthData);

之前:

var length = BitConverter.ToInt32(lengthData, 0);