2011-07-10 88 views
1

有人可以解釋在c#中的異步套接字?我只是跟着從MSDN樣本,這裏是我的代碼部分:C#異步服務器套接字定義?

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. 

    // .... 
} 

我把「Thread.sleep代碼(100000)」後serverSocket.EndAccept,我發現了剩餘的請求不被接受。這是示例輸出:

  1. 如果Thread.sleep代碼(100000)被禁用/評論的,控制檯顯示:
    • 服務器線程#10
    • 客戶線程#11
    • 服務器線程# 10
    • 客戶線程#11
    • 服務器線程#10
    • 客戶線程#11
    • 等等...
  2. 如果Thread.sleep代碼(100000)已啓用,控制檯顯示:
    • 服務器線程#10
    • 客戶線程#11
    • ...沒有在第一個請求完成之前接受其他客戶端請求。

對這種情況的任何解釋?由於

回答

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

    // .... 
} 
+0

此外,在這種情況下,你不需要'而(停止!)'在'開始()'方法,只是某種等待保證主線程不終止。否則,你會有兩點接受不明顯的新連接。 –