关闭旋转异步套接字是否会使侦听器停止侦听?

时间:2012-03-19 16:58:42

标签: c# sockets asynchronous network-programming

以下摘录自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);
}

关闭在AcceptCallback方法中从AsyncState创建的套接字是否会关闭在StartListening方法中创建的侦听器套接字?

真的我的问题是,如果我在线程池上分离socket接收,对数据执行某些操作,然后关闭套接字,我实际上是关闭整个服务器还是只关闭到该客户端的连接? / p>

1 个答案:

答案 0 :(得分:1)

每个接受的连接都会获得一个新套接字。当你完成它,你关闭它。听众会继续倾听。