title: C# How to manually clear TCP socket buffer?
body: <p>I'm writing a TCP server to open a port and talk to some hardware that just sends string data as a byte array.</p>
  
  <p>The environment is in Unity so I went with async callbacks to avoid blocking the program. This seems to work okay, connections are valid, the correct data comes across, I can send messages to the hardware, but the socket buffer never clears. Data just stacks up and does not empty out when I do <code>Socket.EndReceive(ar)</code>.</p>
  
  <p>How does the async loop work? I don't understand why this code is not completing the loop and clearing the buffer. I've spent quite a bit of time trying to understand the process and can't figure out why this code shouldn't work.</p>
  
  <pre><code>    protected TcpListener ListenServer;
      protected Socket SimNetSocket;
      protected byte[] ReadBuffer = new byte[1024];
      protected string MessageBuffer;
  </code></pre>
  
  <p>[....]
  [....]</p>
  
  <pre><code>    public void BeginReceive()
      {
          SimNetSocket.BeginReceive(ReadBuffer, 0, ReadBuffer.Length, SocketFlags.None, EndReceive, null);
      }
  
      protected void EndReceive(IAsyncResult async)
      {
          string msg = "";
  
          try { msg = ByteArrayToString(ReadBuffer); }
          catch (Exception e) { Debug.LogError(e); }
  
          Debug.Log("RAW RECEIVE: " + msg);
          MessageBuffer += msg;
          ReadBuffer = new byte[1024];
          SimNetSocket.EndReceive(async);
          BeginReceive();
      }
  </code></pre>
  
  <p><code>MessageBuffer</code> is a stack which is cleared later in the Update loop where the messages are processed and unrelated to the problem of the <code>ReadBuffer</code> compounding on the socket.</p>
  
  <p>Again, connections are valid (code not shown) and communication is definitely working. I can see data successfully coming and going from both sides but I don't have any control over what the other end hardware is doing. Does it require some implementation to receive these calls and confirm the buffer can clear?</p>
  
  <p>What I actually see is the hardware sending a message, then later another message which gets stacked on it's last message, again, and again, and again. I'm processing every message through the code above, though. So I'm rather confused.</p>