我正在使用InetAddress确定我的服务器是否在线。
如果服务器离线,它将重新启动服务器。
此过程每5分钟循环一次,以再次检查服务器是否在线。
它工作得很好,但现在我需要弄清楚如何指定在检查服务器状态时使用端口43594而不是默认的端口80。
谢谢!下面是我的代码:
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();
}
}
}发布于 2013-02-16 09:54:46
正如我在评论中提到的,根据Javadoc,isReachable的实现方式不允许您控制所选的端口。实际上,如果系统权限允许它这样做,它只会ping机器(ICMP请求)。
手动操作(例如,使用套接字)肯定会起作用,而且不会太复杂和/或更长:
SocketAddress sockaddr = new InetSocketAddress("cloudnine1999.no-ip.org", 43594);
// Create your socket
Socket socket = new Socket();
boolean online = true;
// Connect with 10 s timeout
try {
socket.connect(sockaddr, 10000);
} catch (SocketTimeoutException stex) {
// treating timeout errors separately from other io exceptions
// may make sense
online=false;
} catch (IOException iOException) {
online = false;
} finally {
// As the close() operation can also throw an IOException
// it must caught here
try {
socket.close();
} catch (IOException ex) {
// feel free to do something moderately useful here, eg log the event
}
}
// Now, in your initial version all kinds of exceptions were swallowed by
// that "catch (Exception e)". You also need to handle the IOException
// exec() could throw:
if(!online){
System.out.println("OFFLINE: Restarting Server..");
try {
Runtime.getRuntime().exec("cmd /c start start.bat");
} catch (IOException ex) {
System.out.println("Restarting Server FAILED due to an exception " + ex.getMessage());
}
} 编辑:忘记处理IOException,这也意味着服务器不能工作,添加了
EDIT2:添加了close()可能抛出的IOException的处理
EDIT3:和exec()的异常处理
https://stackoverflow.com/questions/14905982
复制相似问题