繁体   English   中英

从iOS通过Unity C#中的套接字接收以字节为单位的图像

[英]Receive image in bytes through socket in Unity C# from iOS

我试图通过套接字将UIImage从iOS发送到Unity。 我将UIImage转换为NSData并通过异步套接字将其发送到Unity中的服务器。

我正在尝试从客户端(iOS应用程序)接收所有字节,并将这些字节转换为图像,然后将其另存为图像。 我收到文件的所有时间错误,或者为空或损坏。

我不知道这是iOS端,Unity端还是两者都出错。

在我的iOS端,我有:

UIImage *img = images[number];
NSData *dataImg = UIImagePNGRepresentation(img);
[asyncSocket writeData:dataImg withTimeout:-1 tag:1]; // Uses GCDA Async Socket library
[asyncSocket disconnectAfterWriting];

在Unity方面,我有:

    // Data buffer for incoming data.
    byte[] bytes = new Byte[1024];

    // host running the application.
    Debug.Log("Ip " + getIPAddress().ToString());
    IPAddress[] ipArray = Dns.GetHostAddresses(getIPAddress());
    IPEndPoint localEndPoint = new IPEndPoint(ipArray[0], 1755);

    // Create a TCP/IP socket.
    listener = new Socket(ipArray[0].AddressFamily,
                          SocketType.Stream, ProtocolType.Tcp);

    // Bind the socket to the local endpoint and 
    // listen for incoming connections.

    try
    {
        listener.Bind(localEndPoint);
        listener.Listen(10);

        // Start listening for connections.
        while (true)
        {
            Debug.Log("Client Connected");

            Socket handler = listener.Accept();

            while (true) {
                bytes = new byte[1024];
                int bytesRec = handler.Receive(bytes);
                data += Encoding.ASCII.GetString(bytes,0,bytesRec);

                Debug.Log("Bytes rec: " + bytesRec);
                if (bytesRec <= 0) {

                    // Save image in folder from bytes
                    File.WriteAllBytes(@"images/img.png",bytes);

                    break;
                }

            }

            //File.WriteAllBytes(@"images/prova.png",dataImg);

            System.Threading.Thread.Sleep(1);
        }
    }
    catch (Exception e)
    {
        Debug.Log(e.ToString());
    }
}

是空的还是损坏的

bytes = new byte[1024]; 不足以容纳平均图像。 碰撞1024至400,000。

应该是bytes = new byte[400000];

此外,它看起来是否执行此操作,其他未填充的字节也将被写入文件,因此这可能会损坏png文件。

要解决此问题,请更换

System.IO.File.WriteAllBytes(@"images/img.png", bytes);

byte []newImage = new byte[bytesRec];
Array.Copy(bytes, newImage, bytesRec);
System.IO.File.WriteAllBytes(@"images/img.png", bytes);

如果可行,可以稍后进行改进。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM