Manually Sending Keep-Alive Packages

I have a socket called "clientSock". It is connected and working.

I get data using a loop in a stream as follows:

char[] inputChars = new char[1024]; int charsRead = 0; while (!stopNow) { try { if ((charsRead = inputStream.read(inputChars)) != -1) { System.out.println("Firing"); fire_dataRecieved(new String(inputChars, 0, charsRead)); //Fire event. } } catch (IOException e) { //CLIENT HAS DISCONNECTED... connectedClient.disconnect(); stopNow(); } } 

I am going to send β€œsave live package” by simply sending β€œ# KEEP-ALIVE” to the other end.

I can do this using sendStream.print("#KEEP-ALIVE") . Is there a better way to do this? If not, is there an effective way to check for a package? Or is something already there that allows you to check if the other end is alive? clientSock.setKeepAlive(true) does not cut for me. I need to check if the other end is alive on demand.

+4
source share
2 answers

Is there a better way to do this? If not, is there an effective way to check if you have a package? Or is something already there that allows you to check if the other end is alive?

If the problem is with the connection, the TCP stack will tell you very quickly when you send your own keep alive packet. It contains a method to verify that packets were received and in the correct order.

Now, if you want to receive an explicit confirmation that your package has been received, you must send the other end of the confirmation. This is excessive IMHO, but this is what you would need to do.

If you do not receive a response within a reasonable delay (10 seconds is more than enough), and if the TCP stack did not cause any error, this means that the listening side / application on the other side is not doing work. The problem is at the application level, not the TCP stack level.

+1
source

I'm not sure what your question is here. If the other end does not work at the network level, you will get an exception trying to read from the input stream.
If there is a port binding at the other end, but at the application level there is a problem that disconnects the application from the response, then you can use the ACK , as indicated by JVestry.
If your problem is not that you need to distinguish between intermittent network failures and the offline server application.

+1
source

All Articles