Java检查Linux问题上的internet连接
我需要检查互联网连接,所以我写了这个小班:Java检查Linux问题上的internet连接,java,linux,Java,Linux,我需要检查互联网连接,所以我写了这个小班: import java.net.HttpURLConnection; import java.net.URL; import java.util.Timer; import java.util.TimerTask; public class TestConnection { public boolean isInternetAccessed() { try { URL url = new URL("ht
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
public class TestConnection {
public boolean isInternetAccessed() {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(4000);
con.connect();
if (con.getResponseCode() == 200) {
return true;
} else {
return false;
}
} catch (Exception exception) {
System.out.println("No Connection");
return false;
}
}
public static void main(String[] args) {
Timer timer = new Timer();
int period = 10000;
timer.scheduleAtFixedRate(new TimerTask() {
TestConnection internetCheck = new TestConnection();
public void run() {
try {
System.out.println("Starting..................");
System.out.println("Internet Status: " + internetCheck.isInternetAccessed());
System.out.println("Sleeping..................");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}, 0, period);
}
}
这个程序在Java 1.7的Windows机器上运行良好。
但在Linux中,它有一个问题:如果我断开这台机器与internet的连接,运行这个程序,然后我将这台机器连接到internet,程序总是说无法连接
有什么帮助吗?这些程序在Linux环境中也能正常工作。如果存在任何环境问题,请检查您的环境问题。代码没有问题谢谢您的回复。如果我先断开连接,然后运行程序,然后再连接,但该程序仍然表示无法连接(如果我们保持连接,然后运行程序,则可以正常工作)。我已经检查了版本(在Windows和linux中相同)是否为真na当你调用时,当连接不存在时,它将抛出异常na,这将为真。@AnhTuanPham我已经测试了你要求的相同场景connect->disconnect->reconnect。它工作得很好。可能是您没有给系统足够的时间来恢复连接。请等待一些ping,然后检查您的结果哦,这种情况:连接->断开连接->重新连接很好。但场景:disconnect(在启动程序之前)->connect(在程序运行期间)失败(仅在Linux机器上失败,窗口正常)。