简体   繁体   中英

Check service availability from java

How can I check service using java? I found this article , but it is only for checking hostname.

My question is how can I check is service on port x running, ex: myhostname:8080 or myhostname:8099 , I might be running service n or p on those ports but it would be visible trough web if I do it manually, how can I achieve same effect in java?

That snippet sends a ping, which you can't manipulate to achieve what you want. Just open a socket and catch any exceptions.

bool success = true;
try {
  (new Socket(host, port)).close();
} catch (UnknownHostException e) {
  // unknown host
  success = false;
} catch (IOException e) {
  // io exception, service probably not running
  success = false;
}

If you need to detect which service is running, then you need to read the first bytes sent and compare them to what you know each service should send. This might require a few passes back and forth.

Since your services are web, you might want to add a verification of the response code.

boolean available = false;
HttpURLConnection conn = null;
try {
    conn = (HttpURLConnection) new URL("http://yourdomain/").openConnection();
    conn.connect();

    if(conn.getResponseCode() == 200)
        available = true;
}
catch(IOException e) {
}
finally {
    if(conn != null)
        conn.disconnect();
}

Just attempt to connect to the socket.

InetAddress addr = InetAddress.getByName("myhostname");
Socket socket = new Socket(addr, 8099);

If that doesn't thrown an exception then the host is accepting connections on that port. If it isn't you'll typically get a ConnectException .

Just attempt to use the service and deal with the exceptions as they arise. There's generally no point in testing any resource for availability prior to using it. What if it was available when you tested and not when you used it?

You can use sockets to do this.

new Socket("localhost", 8080).getInputStream()

Surround that with a try catch block and you have a solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM