2012-03-19 3 views
1

非同期ソケットをスピンオフすると、リスナーはリッスンを停止しますか? MSDNの例から、この次の抜粋で

public static void StartListening() { 
    // Data buffer for incoming data. 
    byte[] bytes = new Byte[1024]; 

    // Establish the local endpoint for the socket. 
    // The DNS name of the computer 
    // running the listener is "host.contoso.com". 
    IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); 
    IPAddress ipAddress = ipHostInfo.AddressList[0]; 
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000); 

    // Create a TCP/IP socket. 
    Socket listener = new Socket(AddressFamily.InterNetwork, 
     SocketType.Stream, ProtocolType.Tcp); 

    // Bind the socket to the local endpoint and listen for incoming connections. 
    try { 
     listener.Bind(localEndPoint); 
     listener.Listen(100); 

     while (true) { 
      // Set the event to nonsignaled state. 
      allDone.Reset(); 

      // Start an asynchronous socket to listen for connections. 
      Console.WriteLine("Waiting for a connection..."); 
      listener.BeginAccept( 
       new AsyncCallback(AcceptCallback), 
       listener); 

      // Wait until a connection is made before continuing. 
      allDone.WaitOne(); 
     } 

    } catch (Exception e) { 
     Console.WriteLine(e.ToString()); 
    } 

    Console.WriteLine("\nPress ENTER to continue..."); 
    Console.Read(); 

} 

public static void AcceptCallback(IAsyncResult ar) { 
    // Signal the main thread to continue. 
    allDone.Set(); 

    // Get the socket that handles the client request. 
    Socket listener = (Socket) ar.AsyncState; 
    Socket handler = listener.EndAccept(ar); 

    // Create the state object. 
    StateObject state = new StateObject(); 
    state.workSocket = handler; 
    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, 
     new AsyncCallback(ReadCallback), state); 
} 

StartListening方法で作成されたリスナーソケットを閉じAcceptCallback方法でAsyncStateから作成されたソケットをクローズしていますか?

本当に私の質問は、スレッドプールで受信したソケットを受信し、データで何かしてからソケットを閉じるのですが、実際にはサーバー全体を閉じるか、クライアントに接続するだけですか?

答えて

1

各受け入れられた接続が新しいソケットを取得します。あなたがそれで終わったら、あなたはそれを閉じます。リスナーは引き続きリスニングを行います。

関連する問題