Java detect lost connection [duplicate]

2019-01-04 02:28发布

This question already has an answer here:

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?

9条回答
戒情不戒烟
2楼-- · 2019-01-04 02:40

The isConnected()method inside Socket.java class is a little misleading. It does not tell you if the socket is currently connected to a remote host (like if it is unclosed). Instead, it tells you whether the socket has ever been connected to a remote host. If the socket was able to connect to the remote host at all, this method returns true, even after that socket has been closed. To tell if a socket is currently open, you need to check that isConnected() returns true and isClosed() returns false. For example:

boolean connected = socket.isConnected() && !socket.isClosed();
查看更多
戒情不戒烟
3楼-- · 2019-01-04 02:44

You could ping a machine every number of seconds, and this would be pretty accurate. Be careful that you don't DOS it.

Another alternative would be run a small server on a remote machine and keep a connection to it.

查看更多
▲ chillily
4楼-- · 2019-01-04 02:49

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.

查看更多
登录 后发表回答