/* A iterative client that in a loop connects to a server, sends a long sequence, reads its echo, then disconnects. */ import java.net.*; import java.io.*; /** It reads and throws away the responses from the server */ class Helper extends Thread { public static long totalCount; // Total number of characters received public static long totalTime; // total time in receiving private InputStreamReader reader; public Helper(InputStreamReader reader) { this.reader = reader; } public void run() { char[] buffer1 = new char[1024]; // used to read long count = 0; long before, after; before = System.currentTimeMillis(); int n = 0; try { while ( (n = reader.read(buffer1, 0, buffer1.length)) > 0) { count += n; } reader.close(); } catch (Exception e) { System.out.println("Exception in Helper " + "count = " + count + " n = " + n + " " + e.getMessage()); } after = System.currentTimeMillis(); totalCount += count; totalTime += (after-before); System.out.println("The Helper terminated"); System.out.printf( "Time = %7d milliseconds\n" + "Characters = %10d\n" + "DataRate = %10d bytes/second\n", after-before, count, // '1000' is for the change from milliseconds to seconds (long)((double)count*1000/(after-before)) ); } } public class SimpleClient { public final static int DEFAULT_PORT = 9876; private static int port = DEFAULT_PORT; private final static String DEFAULT_SERVER = "LOCALHOST"; private static String serverName = DEFAULT_SERVER; public static void main(String[] args) { // set host and port for server if (args.length >= 2) { serverName = args[0]; port = Integer.parseInt(args[1]); } else if (args.length >= 1) serverName = args[0]; // initialize with junk the buffer array we send to server String hexa = "0123456789ABCDEF"; char[] buffer = new char[1024]; int k = 0, j = 0; while (k < 1024) { buffer[k++] = hexa.charAt(j++); if (j == hexa.length()) j = 0; } // Now write to server while (true) { try { final int numberOfTimes = 10000; // In each iteration, connect, and for numberOfTimes // write and read a buffer Socket client = new Socket(serverName, port); // Create helper thread to read responses from server InputStreamReader reader = new InputStreamReader ( client.getInputStream() ); Thread h = new Helper(reader); h.start(); // Write to server OutputStreamWriter writer = new OutputStreamWriter( client.getOutputStream() ); // For numberOfTimesimes, write the buffer for (int p = 0; p < numberOfTimes; p++) { writer.write(buffer, 0, buffer.length); writer.flush(); } client.shutdownOutput(); // inform server that no more data h.join(); client.close(); System.out.println("Client completes an iteration"); System.out.printf("Average receiving data rate = %d\n", (long)(1000.0*Helper.totalCount/Helper.totalTime)); } catch (Exception e) { System.out.println(e); System.exit(1); } } } }