Skip to content

Instantly share code, notes, and snippets.

@tonyvu2014
Last active August 16, 2016 14:45
Show Gist options
  • Save tonyvu2014/1f86dfa20779aa180b6c to your computer and use it in GitHub Desktop.
Save tonyvu2014/1f86dfa20779aa180b6c to your computer and use it in GitHub Desktop.
Java program to monitor a web server. To use, type in Monitor <web address> <frequency> <timeout>
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class Monitor {
public static void main(String[] args) throws IOException {
if (args.length < 3)
throw new IllegalArgumentException("Invalid number of arguments");
String webAddress = args[0];
int frequency = 0;
int timeout = 0;
try {
frequency = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid value for frequency: " + args[1]);
}
try {
timeout = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid value for timeout: " + args[2]);
}
URL url = new URL(webAddress);
while (true) {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
long startTime = System.currentTimeMillis();
conn.connect();
conn.getInputStream();
conn.setConnectTimeout(timeout);
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
long responseTime = System.currentTimeMillis() - startTime;
System.out.println("Response time: " + responseTime + "ms");
} else {
System.out.println("Server access error");
}
conn.disconnect();
try {
Thread.sleep(frequency);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment