title: C# - TCP Client does not receive server response
body: <p>I am trying to create an asynchronous TCP client for Unity Game project. I am successfully creating a TCP socket connection however I am unable to receive any server response correctly.</p>
  
  <p>Here is my TCP Client Listener code:</p>
  
  <pre><code>#region TCP Client
  
  public static string ServerIP = "127.0.0.1";
  public static int TCPPort = 8080;
  private IPEndPoint serverTCPEndPoint = new IPEndPoint(IPAddress.Parse(ServerIP), TCPPort);
  
  public static Socket TCPClient;
  public Thread SocketThread;
  // ManualResetEvent instances signal completion.  
  private static ManualResetEvent connectDone =
      new ManualResetEvent(false);
  private static ManualResetEvent sendDone =
      new ManualResetEvent(false);
  private static ManualResetEvent receiveDone =
      new ManualResetEvent(false);
  
  // The response from the remote device.  
  private static String response = String.Empty;
  
  private void StartTCPClient()
  {
      // Connect to a remote device.  
      try
      {
          // Create a TCP/IP socket.  
          TCPClient = new Socket(serverTCPEndPoint.AddressFamily,
              SocketType.Stream, ProtocolType.Tcp);
  
          // Connect to the remote endpoint.  
          TCPClient.BeginConnect(serverTCPEndPoint,
              new AsyncCallback(ConnectCallback), TCPClient);
          connectDone.WaitOne();
  
          // Receive the response from the remote device.  
          TCPReceive();
          receiveDone.WaitOne();
  
          // Write the response to the console.  
          Debug.Log("Response received: " + response);
  
      }
      catch (Exception e)
      {
          Debug.Log(e.ToString());
      }
  }
  
  private static void ConnectCallback(IAsyncResult ar)
  {
      try
      {
          // Complete the connection.  
          TCPClient.EndConnect(ar);
  
          Debug.Log("Socket connected to: " + TCPClient.RemoteEndPoint.ToString());
          // Signal that the connection has been made.  
          connectDone.Set();
      }
      catch (Exception e)
      {
          Debug.Log(e.ToString());
      }
  }
  
  private void TCPReceive()
  {
      try
      {
          // Create the state object.  
          StateObject state = new StateObject();
          state.workSocket = TCPClient;
  
          // Begin receiving the data from the remote device.  
          TCPClient.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
              new AsyncCallback(ReceiveCallback), state);
      }
      catch (Exception e)
      {
          Debug.Log(e.ToString());
      }
  }
  
  private void ReceiveCallback(IAsyncResult ar)
  {
      try
      {
          Debug.Log("RECEIVING");
          // Retrieve the state object and the client socket   
          // from the asynchronous state object.  
          StateObject state = (StateObject)ar.AsyncState;
  
          // Read data from the remote device.  
          int bytesRead = TCPClient.EndReceive(ar);
  
          if (bytesRead &gt; 0)
          {
              // There might be more data, so store the data received so far.  
              state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));
  
              // Get the rest of the data.  
              TCPClient.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                  new AsyncCallback(ReceiveCallback), state);
          }
          else
          {
              // All the data has arrived; put it in response.  
              if (state.sb.Length &gt; 1)
              {
                  response = state.sb.ToString();
                  Debug.Log("RECEIVING 2: " + response);
  
                  UnityThread.executeInUpdate(() =&gt;
                  {
                      OnIncomingTCPData(response);
                  });
              }
              // Signal that all bytes have been received.  
              receiveDone.Set();
          }
      }
      catch (Exception e)
      {
          Debug.Log(e.ToString());
      }
  }
  
  #endregion
  </code></pre>
  
  <p>Here is how I start the client:</p>
  
  <pre><code>// Use this for initialization
  void Start()
  {
      int accId = ClientLoginServer.accountId;
      DuloGames.UI.Demo_Chat.worldServer = this;
      if (accId != 0)
      {
          CursorMode cursorMode = CursorMode.Auto;
          Vector2 hotSpot = Vector2.zero;
          SocketThread = new Thread(StartTCPClient);
          SocketThread.IsBackground = true;
          SocketThread.Start();
          Cursor.SetCursor(brownCursor, hotSpot, cursorMode);
          //GameObject go = Instantiate(CharacterNamePrefab) as GameObject;
          GameObject CharacterSelectPanel = GameObject.Find("/Canvas/Panel/CharacterSelectPanel");
      }
      DontDestroyOnLoad(worldserverConnection);
  }
  </code></pre>
  
  <p>All I can see when server is sending data to the Unity TCP client listener is the following line:</p>
  
  <pre><code>Debug.Log("RECEIVING");
  </code></pre>
  
  <p>However this line seems to be not reachable:</p>
  
  <pre><code>Debug.Log("RECEIVING 2: " + response);
  </code></pre>
  
  <p>The following is allowing me to execute the called functions in the main unity thread.</p>
  
  <pre><code>UnityThread.executeInUpdate(() =&gt;
  {
      OnIncomingTCPData(response);
  });
  </code></pre>
  
  <p>Do you have any idea why my Asynchronous TCP client is not working correctly ?</p>