JAVA Specifying port with InetAddress

前端 未结 1 806
醉梦人生
醉梦人生 2021-01-12 07:01

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

If the server is offline it will restart the server.

This process loops every 5 minutes to check

相关标签:
1条回答
  • 2021-01-12 07:18

    As I already mentioned in the comments, according to the Javadoc isReachable 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).

    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 IOException which also means the server isn't functioning, added

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

    EDIT3: and exception handling for exec()

    0 讨论(0)
提交回复
热议问题