title: Receive image in bytes through socket in Unity C# from iOS
body: <p>I am trying to send an <code>UIImage</code> from iOS to Unity through sockets. I convert the <code>UIImage</code> to <code>NSData</code> and send it via async socket to a server in Unity.</p>
  
  <p>I am trying to receive all the bytes from the client (the iOS app) and convert these bytes into an image and save it in the computer as an image. I am getting all time error with the file, either is empty or corrupted. </p>
  
  <p>I don't know if it's an error in the iOS side, Unity side, or both.</p>
  
  <p>In my iOS side, I have:</p>
  
  <pre><code>UIImage *img = images[number];
  NSData *dataImg = UIImagePNGRepresentation(img);
  [asyncSocket writeData:dataImg withTimeout:-1 tag:1]; // Uses GCDA Async Socket library
  [asyncSocket disconnectAfterWriting];
  </code></pre>
  
  <p>In the Unity side, I have:</p>
  
  <pre><code>    // 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 &lt;= 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());
      }
  }
  </code></pre>