I have a socket called 开发者_如何学Python"clientSock". It's connected and working.
I receive data using a loop in a thread, 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 thinking of sending a "keep alive packet" by simply sending "#KEEP-ALIVE" to the other end.
I can do this by using sendStream.print("#KEEP-ALIVE")
. Is there a better way of doing this? If not, is there an efficient way of checking if you got the packet? Or something already there that allows you to check if the other end is alive? clientSock.setKeepAlive(true)
doesn't cut it for me. I need to check if the other end is alive on demand.
Is there a better way of doing this? If not, is there an efficient way of checking if you got the packet? Or something already there that allows you to check if the other end is alive?
If there is an issue with the connection, the TCP stack will tell you very quickly when you send your own keep alive packet. It contains a method to check that packets have arrived and in the right order.
Now, if you want an explicit confirmation that your packet was received, you should have the other end send back a confirmation. It is overkill IMHO, but that's what you would have to do.
If you do not get a response within a reasonable delay (10 seconds is more than enough) and if the TCP stack did not throw some kind of error, it means the listening party/application on the other side is not doing its job. The issue is at the application level, not the TCP stack level.
I am not sure what is your question here.
If the other end is down at network level you will get an exception while trying to read from the input stream.
If the other end has the port bind but there is a problem at the application level that disables the app from responding then an ACK
as mentioned by JVestry can be used.
Unless your problem is that you need to distinguish between intermittent network failures and the server app being offline.
精彩评论