我正在尝试编写一个简单的程序,该程序实时告诉我是否可以连接互联网。这就是我在做什么:
import java.net.Socket;
public class InternetConnection {
public static void main(String[] args) {
String inetAddress = "www.google.com";
int port = 80;
while (true) {
try {
Socket socket = new Socket(inetAddress, port);
System.out.println("Connected to the internet");
} catch (Exception e) {
System.out.println("Not connected to the internet");
}
}
}
}
如果到达
www.google.com
,则会打印出所需的消息。但是,如果我有意断开与Internet的连接以检查其是否有效,它会打印“未连接到Internet”,然后我重新连接并显示“已连接到Internet”,但是当我再次断开连接时,它仍然显示消息“已连接到互联网”。我不知道我在做什么错...P.S.我知道这不是检查是否有互联网连接的最佳方法。
最佳答案
创建套接字并打印连接消息后,请放置延迟时间。
try {
Socket socket = new Socket(inetAddress,port);
System.out.println("Connected to the internet");
}catch(Exception e){
System.out.println("Not connected to the internet");
}
TimeUnit.SECONDS.sleep(5);
您的程序应按预期运行。
关于java - Java程序,用于测试Internet连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47641596/