Dabloons
Dabloons

Reputation: 1512

Does closing a spun off async socket make the listener stop listening?

In this following excerpt from an example on 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);
}

Does closing the socket created from the AsyncState in the AcceptCallback method close the listener socket created in the StartListening method?

Really my question is, if I spin off socket receives on the thread pool, do something with the data, and then close the socket, am I, in fact, closing the entire server or just the connection to that client?

Upvotes: 1

Views: 390

Answers (1)

Roman Starkov
Roman Starkov

Reputation: 61520

Each accepted connection gets a new socket. When you’re done with it, you close it. The listener will keep on listening.

Upvotes: 1

Related Questions