Question: I have the following problem. My client program monitor for availability of server in the local network (using Bonjour, but it does not rally mater). As soon as a server is "noticed" by the client application, the client tries to create a socket: `Socket(serverIP,serverPort);`.

At some point the client can loose the server (Bonjour says that server is not visible in the network anymore). So, the client decide to `close` the socket, because it is not valid anymore.

At some moment the server appears again. So, the client tries to create a new socket associated with this server. But! The server can refuse to create this socket since it (server) has already a socket associated with the client IP and client port. It happens because the socket was closed by the client, not by the server. Can it happen? And if it is the case, how this problem can be solved?

Well, I understand that it is unlikely that the client will try to connect to the server from the same port (client port), since client selects its ports randomly. But it still can happen (just by chance). Right?

Answer: 
the client operating system will not allocate the same port to a new socket so soon. there are several mechanism that prevents it. one of which is the TIME\_WAIT state that reserves the port for some time after the connection is closed.

I wouldn't worry about it.

if you really need to detect disconnection you will have to implement ping/pong protocol, initiated by both the client and the server.
If you close server socket only in case of blocking socket then client socket will be closed but not vice versa.

otherwise it would be better socket in both end. Because socket is a heavy weigt for you system. It will use a local port and a remote port of your system forever.

Thanks
Sunil Kumar Sahoo