Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to stop listening on a Socket

Tags:

People also ask

How do you close a listening socket?

You should use Socket. Shutdown() and then Socket. Close(). Socket.

What is socket listening?

Conceptually, a server socket listens on a known port. When an incoming connection arrives, the listening socket creates a new socket (the “child” socket), and establishes the connection on the child socket.

How do sockets communicate?

Socket addresses An application can communicate with a remote process by exchanging data with TCP/IP by knowing the combination of protocol type, IP address, and port number. This combination is often known as a socket address. It is the network-facing access handle to the network socket.


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?