Java检测丢失的连接 [英] Java detect lost connection

查看:139
本文介绍了Java检测丢失的连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用例如PuTTY和我的连接丢失(或当我在Windows上执行手动 ipconfig / release )时,它直接响应并通知我的连接丢失。

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.

我想创建一个Java程序来监视我的互联网连接(到某些可靠的服务器),记录我的互联网失败时的日期/时间。

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.

我尝试使用 Socket.isConnected()方法,但将永远返回true。如何在Java中这样做?

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

推荐答案

/写从套接字。如果操作失败,那么您有时会丢失连接。

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.

这篇关于Java检测丢失的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆