JAVA 使用 InetAddress 指定端口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14905982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:48:10  来源:igfitidea点击:

JAVA Specifying port with InetAddress

javainetaddress

提问by Cloudnine1999

I am using InetAddress to determine if my server is online.

我正在使用 InetAddress 来确定我的服务器是否在线。

If the server is offline it will restart the server.

如果服务器离线,它将重新启动服务器。

This process loops every 5 minutes to check once again if the server is online.

此过程每 5 分钟循环一次,以再次检查服务器是否在线。

It works fine but now I need to figure out how to specify that I want to use port 43594 when checking the server status instead of the default port 80.

它工作正常,但现在我需要弄清楚如何在检查服务器状态而不是默认端口 80 时指定我要使用端口 43594。

Thanks! Here's my code:

谢谢!这是我的代码:

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();
        }
    }
}

EDIT:

编辑:

Okay so I took someones advice and I made it into this. But now when I uncomment this line.. Runtime.getRuntime().exec("cmd /c start start.bat");

好的,所以我接受了某人的建议,并将其纳入其中。但是现在当我取消注释这一行时.. Runtime.getRuntime().exec("cmd /c start start.bat");

I get this error..

我收到这个错误..

error: unreported exception IOException; must be caught or declared to be thrown

error: unreported exception IOException; must be caught or declared to be thrown

This is my current code:

这是我当前的代码:

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();
        }
    }
}

回答by fvu

As I already mentioned in the comments, according to the JavadocisReachable isn't implemented in a way that would allow you to control the selected port. Actually, if it is allowed to do so by system privileges it will just ping the machine (ICMP request).

正如我在评论中已经提到的,根据JavadocisReachable 没有以允许您控制所选端口的方式实现。实际上,如果系统权限允许这样做,它只会ping 机器(ICMP 请求)。

Doing it manually (ie, using a socket) will certainly work and isn't really more complicated and/or longer:

手动执行(即使用套接字)肯定会起作用,并且不会更复杂和/或更长:

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());
    }
}        

EDIT: forgot to handle IOExceptionwhich also means the server isn't functioning, added

编辑:忘记处理IOException这也意味着服务器无法运行,补充说

EDIT2: added the handling of the IOException that close() can throw

EDIT2:添加了 close() 可以抛出的 IOException 的处理

EDIT3: and exception handling for exec()

EDIT3: 和 exec() 的异常处理