Under rare conditions, the WaitOne in the code below returns false even though the socket has more than the requested data in the Available property. I don't understand why the WaitOne would return false when the data is ready. The network device I'm communicating with is connected to a switch that my computer is connected to. This smells like a software issue, but I suppose it could be other network traffic. Does anyone see anything wrong with how the BeginReceive/WaitOne is being used here?
// The tmpBuffer is code below is defined as:
Byte[] tmpBuffer = new byte[16];
// The following code is in a loop that runs until the entire packet is received
while (packet not received)
// :
// Attempt to get the next block (16-bytes) of data. Since we don't always know how much
// data is coming in, this code always gets 16-bytes at a time. First it tries to
// read 16 bytes. If it only gets 14, for example, then it will read 2 bytes. This
// makes the encyrption easy as it needs to be on a 16-byte block.
IAsyncResult ar = _server.BeginReceive(tmpBuffer, count, tmpBuffer.Length - count, SocketFlags.None, null, null);
// Wait for receive to complete OR timeout in case connection is lost
if (ar.AsyncWaitHandle.WaitOne(_receiveTimeoutMs)) // timeout is 300ms
{
int temp = _server.EndReceive(ar);
if (temp == 0)
{
_server.Close();
throw new ApplicationException("Lost connection!");
}
count += temp;
//Debug.WriteLine("Got data");
}
else
{
sscLogger.LogWarning("Receive timed out...closing socket: rxStartTime=" + rxStartTime.ToString("h:mm:ss.ffff"));
sscLogger.LogWarning("_server.Available=" + _server.Available.ToString() + ", requested=" + (tmpBuffer.Length - count).ToString());
Thread.Sleep(100);
sscLogger.LogWarning("_server.Available=" + _server.Available.ToString() + ", requested=" + (tmpBuffer.Length - count).ToString());
_server.Close();
throw new ApplicationException("Receive timed out");
}
The output of my logging code above is:
[W] 2/26/2015 11:49:17.6082 AM: Receive timed out...closing socket: rxStartTime=11:49:17.3082
[W] 2/26/2015 11:49:17.6102 AM: _server.Available=32, requested=16
[W] 2/26/2015 11:49:17.7123 AM: _server.Available=32, requested=16