C#异步服务器套接字定义?

时间:2011-07-10 14:59:30

标签: c# sockets asynchronous

有人可以解释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)”,我发现其余的请求都没有被接受。这是示例输出:

  1. 如果Thread.Sleep(100000)被禁用/注释,控制台会显示:
    • 服务器线程#10
    • 客户线程#11
    • 服务器线程#10
    • 客户线程#11
    • 服务器线程#10
    • 客户线程#11
    • 等......
  2. 如果启用了Thread.Sleep(100000),控制台会显示:
    • 服务器线程#10
    • 客户线程#11
    • ...在第一个请求完成之前,没有其他客户请求被接受。
  3. 对这种情况的任何解释?感谢

1 个答案:

答案 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);

    // ....
}