在极少数情况下,即使套接字在Available属性中的请求数据多于请求数,下面代码中的WaitOne也会返回false。我不明白为什么WaitOne会在数据准备好后返回false。我正在与之通信的网络设备连接到我的计算机所连接的交换机。这有点像软件问题,但我想它可能是其他网络流量。有没有人看到在这里使用BeginReceive / WaitOne有什么问题?
// 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");
}
上面我的日志记录代码的输出是:
[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