title: C# stream out of order when using TCP send/receive
body: <p>I was creating a small client/server application when I encountered something that seemed to be a mixup in the TCP streem, so I wrote a small test application</p>
  
  <p>The server just creates a TCP socket and sends an incrementing counter</p>
  
  <pre><code>IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 7777);
  Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  socket.Bind(ipEndPoint);
  socket.Listen(10);
  
  Socket clientSocket = socket.Accept();
  
  byte test = 0;
  while (true)
  {
      if (clientSocket.Send(new byte[] { test }, 0, 1, SocketFlags.None) == 1)
      {
          test++;
      }
  }
  </code></pre>
  
  <p>As this is a TCP stream I would expect a stream at the client that just goes from 0 to 255 and so on.</p>
  
  <p>Using the following at the client:</p>
  
  <pre><code>IPEndPoint ipEndPoint = new IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 7777);
  Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  socket.Connect(ipEndPoint);
  
  byte[] buffer = new byte[20000];
  byte last = 255;
  while (true)
  {
      int bytesRead = socket.Receive(buffer);
  
      for (int i = 0; i &lt; bytesRead; i++)
      {
          if (buffer[i] != (byte)(last+1))
          {
              //problem here
          }
          last = buffer[i];
      }
  }
  </code></pre>
  
  <p>The if condition should never return true but it does. After I analyzed the stream at the client it showed that quite often the buffer contains sequences like 000 001 002 003 004 005 006 102 103 104 105.</p>
  
  <p>What am I missing here? I always thought TCP would ensure in order delivery at the TCP level.</p>
  
  <p><strong>Update</strong>: Thorarin pointed to the correct solution. Zone Alarm was messing around with the stream (or probably with the packets). I am going to uninstall this software.</p>