同一ソケットから HTTP リクエストを繰り返し実行するクライアント(修正版)
同一ソケットから HTTP リクエストを繰り返し実行するクライアント - Shammerismを実際に動作させてみたが、一部期待通りに動作しなかったので修正。ただ、マルチバイト文字を問題なくハンドルできるようにするのは難しそうだ。当然だが、サーバー側が Keep-Alive をサポートしている必要もある。
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++ ) { System.out.println("=============================="); System.out.println((i + 1) + " times try start!"); System.out.println("=============================="); int responseBodyContentLength = 0; 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.equals("") ){ System.out.println(""); break; } else if( line.startsWith("Content-Length:") ){ String[] array = line.split(": "); responseBodyContentLength = Integer.parseInt(array[1]); } else { System.out.println(line); } } // Read Response Body(supported only ascii) for( int j = 0 ; j < responseBodyContentLength ; j++ ){ System.out.print((char)reader.read()); } System.out.println("=============================="); System.out.println((i + 1) + " times try finish!"); System.out.println("=============================="); 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){} } } } }