Search code examples
javasocketsserversocket

ServerSocket vs Socket -- closing the socket


Both ServerSocket and Socket have the method close() to close the socket.

What is the difference between the two?

Suppose, on the server side,

ServerSocket serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept();  
...

In this case, how is

socket.close();

different from

serverSocket.close();

if any?

TIA.


Solution

  • ServerSocket sets up a listener from which you can accept any number of Socket connections. Closing a Socket closes that one connection; closing the ServerSocket means the listener is closed and can no longer accept connections to that port.