TcpClient BottleNeck
<p>I'm trying to create a self-contained class which maintains a Tcp connection to a server.</p>

<p>I'm using the following class variables:</p>

<pre><code>TcpClient tcpClient;
NetworkStream networkStream;
BinaryReader mReader;
BinaryWriter mWriter;
</code></pre>

<p>And initializing them using the following code:</p>

<pre><code>tcpClient = new TcpClient(host, 443);
networkStream = tcpClient.GetStream();
mReader = new BinaryReader(networkStream);
mWriter = new BinaryWriter(networkStream);

receiveMessage = new Thread(new ThreadStart(ReceiveMessages));
receiveMessage.Start();
</code></pre>

<p>I'm using blocking calls for the reading.  Each packet coming from the server is prefixed with 4 bytes (an int) which define the exact packet size.  I'm using a class I wrote named ByteBuffer which has a List(Byte) to store the bytes once they come in.  The class has functions which pull ints and other types off of the top of the byte list using ReadInt(), ReadString() etc, according to the server protocol.</p>

<p>Here is the Receiver thread:</p>

<pre><code>private void ReceiveMessages()
{
    while (tcpClient.Connected)
    {
        if (tcpClient.Available &gt;= 4)
        {
            try
            {
                ByteBuffer message = new ByteBuffer();
                message.AddBytes(mReader.ReadBytes(4));
                int mSize = message.ReadInt();
                message.AddBytes(mReader.ReadBytes(mSize - 4));
                MessageProcessor.Process(message);
            }
            catch (Exception ex)
            {
               Print(ex.Message);
            }
        }
        Thread.Sleep(1);
    }
    Print("Receiver thread terminated.");
    Reconnect();
}
</code></pre>

<p>For reference, the MessageProcessor is a static class which looks at the packet information and responds to the server appropriately.</p>

<p>My problem is that when the traffic on the connection begins to get really high, the responses begin to get significantly delayed.  I'm wondering, is there something I'm doing incorrectly as far as the tcp connection is concerned?  Should I try writing an asynchronous version of the class instead?  Is the C# List object too slow to be used this frequently (in the ByteBuffer)?</p>

<p>This is really my first attempt at network programming, so any advice would be extremely helpful.</p>

<p>Thanks.</p>
