Skip to content

Instantly share code, notes, and snippets.

@boly38
Last active February 10, 2019 17:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boly38/0a043df5c9a9427d867a4cd16162ac5c to your computer and use it in GitHub Desktop.
Save boly38/0a043df5c9a9427d867a4cd16162ac5c to your computer and use it in GitHub Desktop.
Java Simple Socket Check
package com.github.gist.it;
import java.net.InetSocketAddress;
import java.net.Socket;
public class NetUtils {
/**
* check if a given server is listening on a given port in the limit of timeoutMs
* @param serverHost server hostname (or ip)
* @param serverPort server port
* @param timeoutMs timeout in ms
* @param exDetails message to provide as exception details when unable to connect
*/
public static void checkServerListening(String serverHost, int serverPort, int timeoutMs, String exDetails) {
try (Socket s = new Socket()) {
s.connect(new InetSocketAddress(serverHost, serverPort), timeoutMs);
} catch (Exception e) {
String errMsg = String.format("Can't connect to [%s:%d] (timeout was %d ms) - %s, - %s",
serverHost, serverPort, timeoutMs, exDetails, e.getMessage());
throw new IllegalStateException(errMsg);
}
}
}
@boly38
Copy link
Author

boly38 commented Aug 7, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment