我正在编写一个套接字服务器,我注意到如果它收到一个空的套接字缓冲区,它将导致套接字异常。在接收调用中,如何检测和处理空缓冲区并在套接字关闭之前将 -1 响应发送回客户端?
代码:
try
{
byte[] byteBuffer = new Byte[1024];
int size = m_clientSocket.Receive(byteBuffer);
if (size > 0)
{
ParseReceiveBuffer(byteBuffer, size);
}
else
{
m_clientSocket.Send(BitConverter.GetBytes(-1));
}
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.WouldBlock ||
ex.SocketErrorCode == SocketError.IOPending ||
ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
{
// socket buffer is probably empty, wait and try again
Thread.Sleep(1000);
}
// connection was unexpectively closed
}