【问题标题】:Receive image in bytes through socket in Unity C# from iOS通过 iOS 中的 Unity C# 中的套接字以字节为单位接收图像
【发布时间】:2016-06-15 21:58:27
【问题描述】:

我正在尝试通过套接字将 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());
    }
}

【问题讨论】:

    标签: c# ios arrays sockets unity3d


    【解决方案1】:

    要么是空的,要么是损坏的

    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);
    

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

    【讨论】:

      猜你喜欢
      • 2019-10-05
      • 2017-02-25
      • 1970-01-01
      • 2022-01-18
      • 2014-03-25
      • 2023-03-05
      • 1970-01-01
      • 2010-10-19
      • 2019-02-18
      相关资源
      最近更新 更多