同一ソケットから HTTP リクエストを繰り返し実行するクライアント
ちょっと書いてみたのでメモ。
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; public class RepeatClient { public static void main(String[]args)throws Exception{ if( args.length != 4 ){ System.out.println("Usage: java RepeatClient $HOST $PORT $URI $REPEAT_COUNT\n"); System.exit(1); } Socket socket = null; BufferedReader reader = null; BufferedWriter writer = null; try { socket = new Socket(args[0], Integer.parseInt(args[1])); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); int repeatCount = Integer.parseInt(args[3]); for( int i = 0 ; i < repeatCount ; i++ ) { writer.write("GET " + args[2] + " HTTP/1.1\r\n"); writer.write("Host: " + args[0] + "\r\n"); writer.write("Connection: Keep-Alive\r\n"); writer.write("\r\n"); writer.flush(); while(true){ String line = reader.readLine(); if( line == null ){ break; } System.out.println(line); } try { Thread.sleep(1 * 1000); } catch(InterruptedException ignore){} } } catch(Exception e){ e.printStackTrace(); } finally{ if( writer != null ){ try { writer.close(); } catch(Exception ignore){} } if( reader != null ){ try { reader.close(); } catch(Exception ignore){} } if( socket != null ){ try { socket.close(); } catch(Exception ignore){} } } } }
以下のように jar ファイルにして実行する。
$ cat MANIFEST.MF Main-Class: RepeatClient $ jar cmf MANIFEST.MF RepeatHttpClient.jar RepeatClient.class $ java -jar RepeatHttpClient.jar Usage: java RepeatClient $HOST $PORT $URI $REPEAT_COUNT $