Alex Rivera | Logout

Proper way to stop listening on a Socket

Asked 2009-01-16T22:47:03.657
23

I have a server that listens for a connection on a socket:

public class Server
{
    private Socket _serverSocket;

    public Server()
    {
        _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        _serverSocket.Bind(new IPEndPoint(IPAddress.Any, 1234));
        _serverSocket.Listen(1);
    }

    public void Start()
    {
        _serverSocket.BeginAccept(HandleAsyncConnectionMethod, null);
    }

    public void Stop()
    {
        //????? MAGIC ?????
    }

    //... rest of code here
}

What is the correct (clean) way to close down the socket?

Is it sufficient to call:

_serverSocket.Disconnect(true);

in the Stop() method? or is there other work that needs to happen to close the connection cleanly?

Edit
Report

1 Answer

3

Since you are listening for incoming TCP connections, you could use System.Net.Sockets.TcpListener which does have a Stop() method. It does not have asynchronous operations though.

answered 2009-01-16T23:03:50.113

Your Answer