Java detect lost connection


When I'm using e.g. PuTTY and my connection gets lost (or when I do a manual ipconfig /release on Windows), it responds directly and notifies my connection was lost.

I want to create a Java program which monitors my Internet connection (to some reliable server), to log the date/times when my internet fails.

I tried use the Socket.isConnected() method but that will just forever return "true". How can I do this in Java?

Best Solution

Well, the best way to tell if your connection is interrupted is to try to read/write from the socket. If the operation fails, then you have lost your connection sometime.

So, all you need to do is to try reading at some interval, and if the read fails try reconnecting.

The important events for you will be when a read fails - you lost connection, and when a new socket is connected - you regained connection.

That way you can keep track of up time and down time.