Last active
August 16, 2016 14:45
-
-
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>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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