package MV3500Cohort2024JulySeptember.homework2.Williams; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; /** * Client file for HW2. * * @author ethanjwilliams */ public class HW2Client { /** * Default constructor */ public HW2Client() { } static String DESTINATION_HOST = "localhost"; static int DESTINATION_PORT = 2317; static int MAX_LOOP_COUNT = 1; /** * @param args command-line arguments */ public static void main(String[] args) { if (args.length > 0) { DESTINATION_HOST = args[0]; } if (args.length > 1) { DESTINATION_PORT = Integer.parseInt(args[1]); } if (args.length > 2) { MAX_LOOP_COUNT = Integer.parseInt(args[2]); } System.out.println("======================================================="); for (int loopCount = 1; loopCount <= MAX_LOOP_COUNT; loopCount++) { System.out.println(HW2Client.class.getName() + " creating new socket:"); long startTime = System.currentTimeMillis(); Socket socket = null; BufferedReader br = null; PrintWriter pw = null; try { socket = new Socket(DESTINATION_HOST, DESTINATION_PORT); InputStream is = socket.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); OutputStream os = socket.getOutputStream(); pw = new PrintWriter(os, true); String serverMessage = br.readLine(); System.out.println("Server: " + serverMessage); String clientResponse = "Ethan"; pw.println(clientResponse); System.out.println("Client: " + clientResponse); String serverFinalResponse = br.readLine(); long readTime = System.currentTimeMillis(); long timeLength = readTime - startTime; System.out.println("Server response: " + serverFinalResponse); System.out.println(HW2Client.class.getName() + ": time msec required for read = " + timeLength); System.out.println("======================================================="); } catch (IOException e) { System.out.println("Problem with " + HW2Client.class.getName() + " networking:"); System.out.println("Error: " + e); if (e instanceof java.net.BindException) { System.out.println("*** Be sure to stop any other running instances of programs using this port!"); } } finally { try { if (br != null) { br.close(); } if (pw != null) { pw.close(); } if (socket != null && !socket.isClosed()) { socket.close(); } } catch (IOException e) { System.out.println("Error closing resources: " + e); } } } System.out.println(HW2Client.class.getName() + " complete"); } }