I'm using .Net Sockets to handle communications between my server and my client. Sometimes, though, the receiving TcpClient misses a transmissions. It happens on and off, but when it does happen, it happens consistently. It seems to happen most often when I'm sending 3 messages (packets?) in rapid succession, which makes me think that the way that I'm handling the messages on the client side (I'm pretty sure the server is sending them properly) incorrectly.
This is the code that I use to handle the incoming messages:
if (m_Client.Connected == true) // m_Client is of type System.Net.Sockets.TcpClient
{
NetworkStream stream = m_Client.GetStream();
Byte[] buffer = new Byte[100000];
Int32 count = stream.Read(buffer, 0, buffer.Length);
while (count > 0)
{
Byte[] receivedBytes = new Byte[count];
Buffer.BlockCopy(buffer, 0, receivedBytes, 0, count);
lock (m_ReceivedQueue)
{
m_ReceivedQueue.Enqueue(receivedBytes);
}
count = stream.Read(buffer, 0, buffer.Length);
}
}
What's going on is that I set up the TcpClient to wait for a message, and when one comes in, I stick the message on to a queue, which processes the message, and then wait for a new message. The queue shouldn't be locked for long, as this is what I do with it (in another thread):
Byte[] bytes = null;
lock (m_ReceivedQueue)
{
if (m_ReceivedQueue.Count > 0)
{
bytes = m_ReceivedQueue.Dequeue();
}
}
if (bytes != null)
{
// Do stuff
}
In both cases, I've tried to lessen the time that the queue stays locked, and I think I have that down to a minimum, but I'm still experiencing the missed messages. I've even tried moving the lock stuff into a background worker thread in the listening code:
if (m_Client.Connected == true)
{
NetworkStream stream = m_Client.GetStream();
Byte[] buffer = new Byte[100000];
Int32 count = stream.Read(buffer, 0, buffer.Length);
while (count > 0)
{
Byte[] receivedBytes = new Byte[count];
Buffer.BlockCopy(buffer, 0, receivedBytes, 0, count);
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += delegate
{
lock (m_ReceivedQueue)
{
m_ReceivedQueue.Enqueue(receivedBytes);
}
};
backgroundWorker.RunWorkerAsync();
count = stream.Read(buffer, 0, buffer.Length);
}
}
But that didn't help, either.
I'm sending 3 messages, and the first and second get received just fine, but the third just isn't getting noticed by the client. Is my network model flawed? Should I be using WCF or something? Do the things I've tried suggest that maybe the problem is elsewhere?
Thank you.
Without order nothing can exist - without chaos nothing can evolve.