0

I am working on socket programming. Is there any way to detect the server disconnection to the client immediately.

I used socket.isConnected , isBound methods but I did’t get good results.

I tried to read the data from the stream continuously to check but it blocks that if data is not available or return from the server and I don’t want to write garbage data to send each time to check the connection with the server.

Please suggest any suggestions.

Prabal
  • 1
  • 1

1 Answers1

-1

It depends on which socket type you're using. Even then it is unavoidable to implement a keep-alive mechanism for your specific purpose.

The default TCP keep-alive mechanism checks every 2 hours (!) if the connection still exists. This default value can be changed but it may not work. See:

Does a TCP socket connection have a "keep alive"?

UDP on the other hand is stateless; there is no connection. The context in which socket.isConnected() should be interpreted is whether it's bound to a local port.

For UDP it is an absolute requirement to send ping/pongs back and forth to determine connectivity.

Hope it helps.

Community
  • 1
  • 1
whitebrow
  • 2,015
  • 21
  • 24
  • `isConnected()` for UDP doesn't indicate anything about a local port. It indicates whether the socket is connected to a remote address. – user207421 Aug 20 '15 at 15:32
  • This is untrue... since UDP is stateless there never is a connection with a remote address. 'Connection' in this regard means that the DatagramSocket will simply discard any incoming datagrams from other addresses. Technically there never is a real connection. – whitebrow Aug 20 '15 at 15:36