title: NetworkStream dirty during client/server TCP communication
body: <p>I've both a client and a server communicating through TCP.
  The client uses the NetworkStream to send info to the server that reads it back, then the process continues until the user wants to exit and close the connection. The problem is that the NetworkStream is dirty with a previous write. So let's suppose the client sends the string "aa "during the first time, and "b" during the second. On the second read the server will get "ba". What's missing here? Shouldn't the NetworkStream be consumed during the server reads? Here`s the relevant code ...</p>
  
  <p>Server</p>
  
  <pre><code>        while (true)
          {
              try
              {
                  NetworkStream clientStream = tcpClient.GetStream();
                  bytesRead = clientStream.Read(messageBytes, 0, messageBytes.Length);
              }
              catch (Exception ex)
              {
                  LogToConsole(clientEndPoint, String.Format("[ERROR] Exception: {0}", ex.Message));
                  break;
              }
  
              if (bytesRead == 0)
              {
                  LogToConsole(clientEndPoint, "Client has disconnected");
                  break;
              }
  
              messageCounter++;
              string message = Encoding.ASCII.GetString(messageBytes);
              message = message.Substring(0, message.IndexOf('\0'));
              LogToConsole(clientEndPoint, String.Format(" &gt;&gt; [{0}] Message received: {1}", messageCounter, message));
          }
  </code></pre>
  
  <p>CLIENT</p>
  
  <pre><code>            string infoToSend = null;
              do
              {
                  Console.Write(" &gt;&gt; Info to send: ");
                  infoToSend = Console.ReadLine();
  
                  if (!String.IsNullOrEmpty(infoToSend))
                  {
                      NetworkStream serverStream = client.GetStream();
                      byte[] buffer = Encoding.ASCII.GetBytes(infoToSend);
                      serverStream.Write(buffer, 0, buffer.Length);
                      serverStream.Flush();
                  }
              } while (!String.IsNullOrEmpty(infoToSend));
  </code></pre>
  
  <h1>SOLUTION</h1>
  
  <p>As Douglas spotted, the buffer (messageBytes) was dirty with a previous read. I ended up with this code for the server (I posted the entire code as it might be useful for somebody else):</p>
  
  <pre><code>namespace Gateway
  {
      class Program
      {
          static void Main(string[] args)
          {
              int requestCount = 0;
  
              TcpListener serverSocket = new TcpListener(IPAddress.Any, 8888);
              serverSocket.Start();
              LogToConsole("Server Started. Waiting for clients ...");
  
              while ((true))
              {
                  try
                  {
                      TcpClient client = serverSocket.AcceptTcpClient();
                      requestCount++;
                      LogToConsole(String.Format("Connection from {0} accepted. Request #{1}", client.Client.RemoteEndPoint.ToString(), requestCount));
  
                      Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientConnection));
                      clientThread.IsBackground = true;
                      clientThread.Start(client);
                      LogToConsole(String.Format("Thread #{0} created to handle connection from {1}", clientThread.ManagedThreadId, client.Client.RemoteEndPoint.ToString()));
                      LogToConsole("Waiting for next client ...");
                  }
                  catch (Exception ex)
                  {
                      LogToConsole(ex.ToString());
                      break;
                  }
              }
          }
  
          static void HandleClientConnection(object client) 
          {
              TcpClient tcpClient = (TcpClient)client;
  
              byte[] messageBytes = new byte[1024];
              int bytesRead;
              int messageCounter = 0;
  
              string clientEndPoint = tcpClient.Client.RemoteEndPoint.ToString();
  
              while (true)
              {
                  try
                  {
                      NetworkStream clientStream = tcpClient.GetStream();
                      bytesRead = clientStream.Read(messageBytes, 0, messageBytes.Length);
                  }
                  catch (Exception ex)
                  {
                      LogToConsole(clientEndPoint, String.Format("[ERROR] Exception: {0}", ex.Message));
                      break;
                  }
  
                  if (bytesRead == 0)
                  {
                      LogToConsole(clientEndPoint, "Client has disconnected");
                      break;
                  }
  
                  messageCounter++;
                  string message = Encoding.ASCII.GetString(messageBytes, 0, bytesRead);
                  LogToConsole(clientEndPoint, String.Format(" &gt;&gt; [{0}] Message received: {1}", messageCounter, message));
              }
  
              LogToConsole(clientEndPoint, "Closed connection to client");
              tcpClient.Close();
          }
  
          static void LogToConsole(string clientEndPoint, string message)
          {
              int threadId = Thread.CurrentThread.ManagedThreadId;
              string time = DateTime.Now.ToString("HH:mm:ss");
              Console.WriteLine("{0} [{1}, {2}] {3}", time, threadId, clientEndPoint, message);
          }
  
          static void LogToConsole(string message)
          {
              int threadId = Thread.CurrentThread.ManagedThreadId;
              string time = DateTime.Now.ToString("HH:mm:ss");
              Console.WriteLine("{0} [{1}] {2}", time, threadId, message);
          }
      }
  }
  </code></pre>