有人可以解释c#中的异步套接字吗?我刚刚跟踪了MSDN中的示例,这是我的代码的一部分:
public void Start()
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Any, port));
serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 10000);
serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 10000);
serverSocket.Listen(1000);
while (!stop)
{
Console.WriteLine("Server Thread #" + Thread.CurrentThread.ManagedThreadId);
allDone.Reset();
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), serverSocket);
allDone.WaitOne();
}
}
private void AcceptCallback(IAsyncResult ar)
{
allDone.Set();
Socket serverSocket = (Socket)ar.AsyncState;
Socket clientSocket = serverSocket.EndAccept(ar);
Console.WriteLine("Client Thread #" + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(100000); <----- All request is stopped, no response returned.
// ....
}
我在serverSocket.EndAccept之后放了“Thread.Sleep(100000)”,我发现其余的请求都没有被接受。这是示例输出:
对这种情况的任何解释?感谢
答案 0 :(得分:1)
一旦你打电话给
Socket clientSocket = serverSocket.EndAccept(ar);
您需要在服务器套接字上再次调用BeginAccept
方法。
所以函数看起来像这样:
private void AcceptCallback(IAsyncResult ar)
{
allDone.Set();
Socket serverSocket = (Socket)ar.AsyncState;
Socket clientSocket = serverSocket.EndAccept(ar);
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), serverSocket);
Console.WriteLine("Client Thread #" + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(100000);
// ....
}