我想实现一个异步服务器套接字。为此,我正在研究Microsoft Docs。还有一些我不理解的东西。
有一个回调函数调用ReceiveCallback
。而且据我所知,每次收到消息时都会调用此函数。但是为什么我们要检查bytesRead > 0
是否呢?这将意味着未收到任何消息,并且如果未收到任何消息,则不会调用回调函数。结果,我再也没进入else condition
并且我的response
从未设置过...
private static void ReceiveCallback( IAsyncResult ar )
{
try {
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
// Get the rest of the data.
client.BeginReceive(state.buffer,0,StateObject.BufferSize,0, ReceiveCallback, state);
} else
{
// All the data has arrived; put it in response.
if (state.sb.Length > 1) {
response = state.sb.ToString();
}
// Signal that all bytes have been received.
receiveDone.Set();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}