简体   繁体   中英

How to detect the server disconnection to the client immediately in Java(Android) socket communication

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM