我正在使用 InetAddress 来确定我的服务器是否在线。
如果服务器离线,它将重新启动服务器。
此过程每 5 分钟循环一次,以再次检查服务器是否在线。
它工作得很好,但现在我需要弄清楚如何指定在检查服务器状态时使用端口 43594 而不是默认的端口 80。
谢谢!这是我的代码:
```java InetAddress address = InetAddress.getByName("example.com"); if (!address.isReachable(5000)) { // restart server } ```
请注意,以上代码中没有指定端口。
import java.net.InetAddress;
public class Test extends Thread {
public static void main(String args[]) {
try {
while (true) {
try
{
InetAddress address = InetAddress.getByName("cloudnine1999.no-ip.org");
boolean reachable = address.isReachable(10000);
if(reachable){
System.out.println("Online");
}
else{
System.out.println("Offline: Restarting Server...");
Runtime.getRuntime().exec("cmd /c start start.bat");
}
}
catch (Exception e)
{
e.printStackTrace();
}
Thread.sleep(5 * 60 * 1000);
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
编辑:
好的,我采纳了某人的建议,把代码改成了这样。但是,现在当我取消注释这行代码时..
Runtime.getRuntime().exec("cmd /c start start.bat");
我会收到这个错误..
error: unreported exception IOException; must be caught or declared to be thrown
这是我的当前代码:
import java.net.*;
import java.io.*;
public class Test extends Thread {
public static void main(String args[]) {
try {
while (true) {
SocketAddress sockaddr = new InetSocketAddress("cloudnine1999.no-ip.org", 43594);
Socket socket = new Socket();
boolean online = true;
try {
socket.connect(sockaddr, 10000);
}
catch (IOException IOException) {
online = false;
}
if(!online){
System.out.println("OFFLINE: Restarting Server..");
//Runtime.getRuntime().exec("cmd /c start start.bat");
}
if(online){
System.out.println("ONLINE");
}
Thread.sleep(1 * 10000);
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
cloudnine1999.no-ip.org:43594
- FThompson