如何检查Java中的Internet连接 [英] How to check internet connectivity in Java

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

问题描述

我正在开发一个需要随时连接互联网的Java项目。

I am working on a Java project which needs to have an internet connection at all times.

我希望我的程序能够在某个时间间隔内检查互联网连接(例如5或10秒)并在没有检测到互联网连接时立即显示消息。

I want my program to keep checking the internet connection at some time intervals (say 5 or 10 seconds) and display a message as soon as no internet connection is detected.

我试图使用isReachable方法来实现此功能,下面是代码 -

I have tried to use the isReachable method to achieve this functionality, below is the code -

try
{
    InetAddress add = InetAddress.getByName("www.google.com");
    if(add.isReachable(3000)) System.out.println("Yes");
    else System.out.println("No");
}
catch (UnknownHostException e) 
{
    System.out.println("unkownhostexception");
} 
catch (IOException e) 
{
    System.out.println("IoException");
}

但此代码始终返回否。这段代码有什么问题?

But this code always returns "No". What is the problem with this code?

谢谢

推荐答案

我所知道的唯一方法是发送一个已知主机的数据包,在某种意义上称为知道它将始终启动并运行并可从主叫站点访问。

The only way I am aware of is sending a packet to some known host, known in the sense that you know it will always be up and running and reachable from the calling site.

但是,例如,如果您选择命名主机,则由于DNS查找失败,ping可能会失败。

However, for example, if you choose a named host, the ping may fail due to a DNS lookup failure.

我认为您不应该担心此问题:您的程序需要Internet连接,这是因为它发送或接收数据。连接不像河流那样是连续概念,而更像是一条道路。因此,只需使用Java标准来处理连接错误:IOExceptiions。当您的程序必须发送数据时,如果网络出现故障,底层API将确保抛出IOE。如果您的程序需要数据,请使用超时或类似的东西来检测网络堆栈中的可能错误并将其报告给用户。

I think you shouldn't worry about this problem: if your program needs an Internet connection, it's because it sends or receives data. Connections are not a continuous concept like a river, but are more like a road. So just use the Java standard for dealing with connection errors: IOExceptiions. When your program must send data, the underlying API will certailnly throw an IOE in the case the network is down. If your program expects data, instead, use a timeout or something like that to detect possible errors in the network stack and report it to the user.

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

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