From ef563a504bc976d81f821eefb4f09c5411354d74 Mon Sep 17 00:00:00 2001 From: rojas <rojas@N619> Date: Fri, 9 Aug 2024 11:56:43 -0700 Subject: [PATCH] Update --- .../homework1/Romero/Homework.java | 8 -- .../homework1/Romero/ReneHW1.java | 117 ++++++++++++++++++ .../homework2/Romero/README.md | 7 ++ .../homework2/Romero/RomeroServerHW2.java | 75 +++++++++++ .../homework2/Romero/TcpExample4Client.java | 84 +++++++++++++ .../Romero/TcpExample4HandlerThread.java | 91 ++++++++++++++ 6 files changed, 374 insertions(+), 8 deletions(-) delete mode 100644 assignments/src/MV3500Cohort2024JulySeptember/homework1/Romero/Homework.java create mode 100644 assignments/src/MV3500Cohort2024JulySeptember/homework1/Romero/ReneHW1.java create mode 100644 assignments/src/MV3500Cohort2024JulySeptember/homework2/Romero/README.md create mode 100644 assignments/src/MV3500Cohort2024JulySeptember/homework2/Romero/RomeroServerHW2.java create mode 100644 assignments/src/MV3500Cohort2024JulySeptember/homework2/Romero/TcpExample4Client.java create mode 100644 assignments/src/MV3500Cohort2024JulySeptember/homework2/Romero/TcpExample4HandlerThread.java diff --git a/assignments/src/MV3500Cohort2024JulySeptember/homework1/Romero/Homework.java b/assignments/src/MV3500Cohort2024JulySeptember/homework1/Romero/Homework.java deleted file mode 100644 index 396d1cfa5f..0000000000 --- a/assignments/src/MV3500Cohort2024JulySeptember/homework1/Romero/Homework.java +++ /dev/null @@ -1,8 +0,0 @@ -package MV3500Cohort2024JulySeptember.homework1.Romero; - -public class Homework { - - public static void main(String args[]) { - System.out.println("Hello world!"); - } -} \ No newline at end of file diff --git a/assignments/src/MV3500Cohort2024JulySeptember/homework1/Romero/ReneHW1.java b/assignments/src/MV3500Cohort2024JulySeptember/homework1/Romero/ReneHW1.java new file mode 100644 index 0000000000..7f828bf387 --- /dev/null +++ b/assignments/src/MV3500Cohort2024JulySeptember/homework1/Romero/ReneHW1.java @@ -0,0 +1,117 @@ +package MV3500Cohort2024JulySeptember.homework1.Romero; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import java.net.ServerSocket; +import java.net.Socket; + +/** + * <p> + * The simplest possible TCP network program, opening a socket and waiting for a reply. + * It listens for any socket connection response, either from telnet (telnet localhost 2317) + * or another program that you write (which we will do later). + * Once a socket connection is established, TcpExample1Telnet simply + * writes a string in response to that connection and finishes, exiting. + * + * <p> + * As an alternative to running the Windows (or other operating system) console, + * you can instead run the NetBeans terminal window. If you are on Windows, + * NetBeans is looking for Cygwin installation (for Unix-like compatibility) + * with details at <a href="https://savage.nps.edu/Savage/developers.html#Cygwin" target="blank">Savage Developers Guide: Cygwin</a>. + * Modifying this program is the basis for Assignment 1. + * </p> + * + * <p> + * Testing the running server program from telnet looks like this: + * </p> + * <pre> + * it154916:projects mcgredo$ <b>telnet localhost 2317</b> + * Trying ::1... + * Connected to localhost. + * Escape character is '^]'. + * This was written by the server + * Connection closed by foreign host. + * </pre> + * <p> + * Notice that "This was written by the server" matches + * what is written by the code below, over the output stream. + * </p> + * + * <p> + * After this first connection the program below drops to + * the bottom of the method, and does not repeat itself. + * In other words, the program exits. + * </p> + * + * @see <a href="../../../src/TcpExamples/TcpExample1TerminalLog.txt" target="_blank">TcpExample1TerminalLog.txt</a> + * @see <a href="../../../src/TcpExamples/TcpExample1NetBeansConsoleTelnet.png" target="_blank">TcpExample1NetBeansConsoleTelnet.png</a> + * @see <a href="../../../src/TcpExamples/TcpExample1NetBeansConsoleTelnet.pdf" target="_blank">TcpExample1NetBeansConsoleTelnet.pdf</a> + * @see <a href="../../../src/TcpExamples/TcpExample1ScreenshotNetcat.png" target="_blank">TcpExample1ScreenshotNetcat.png</a> + * @see <a href="../../../src/TcpExamples/TcpExample1ScreenshotTelnet.png" target="_blank">TcpExample1ScreenshotTelnet.png</a> + * @see <a href="https://savage.nps.edu/Savage/developers.html#Cygwin" target="blank">Savage Developers Guide: Cygwin</a> + * @see <a href="https://savage.nps.edu/Savage/developers.html#telnet" target="blank">Savage Developers Guide: telnet</a> + * + * @author mcgredo + * @author brutzman@nps.edu + */ + +public class ReneHW1 +{ + /** Default constructor */ + public ReneHW1() + { + // default constructor + } + /** + * Program invocation, execution starts here + * @param args command-line arguments + */ + public static void main(String[] args) + { + try + { + System.out.println(ReneHW1.class.getName() + " has started and is waiting for a connection."); + System.out.println(" help: https://savage.nps.edu/Savage/developers.html#telnet"); + System.out.println(" terminal: enter (telnet localhost 2317) or, for macOS (nc localhost 2317)..." ); + + // The ServerSocket waits for a connection from a client. + // It returns a Socket object when the connection occurs. + ServerSocket serverSocket = new ServerSocket(2317); + + // Use Java io classes to write text (as opposed to + // unknown bytes of some sort) to the client + + // The Socket object represents the connection between + // the server and client, including a full duplex connection + try (Socket clientConnection = serverSocket.accept()) // listen, wait here for a client to connect + { + // OK we got something, time to respond! + // Use Java io classes to write text (as opposed to + // unknown bytes of some sort) to the client + OutputStream os = clientConnection.getOutputStream(); + PrintStream ps = new PrintStream(os); + + ps.println("This client response was written by server " + ReneHW1.class.getName()); // to remote client + System.out.println("This server response was written by server " + ReneHW1.class.getName()); // to server console + + // "flush()" in important in that it forces a write + // across what is in fact a slow connection + ps.flush(); + } + + System.out.println(ReneHW1.class.getName() + " completed successfully."); + } + catch(IOException ioe) + { + System.err.println("Exception with " + ReneHW1.class.getName() + " networking:"); // describe what is happening + System.err.println(ioe); + // Provide more helpful information to user if exception occurs due to running twice at one time + + // brute force exception checking, can be brittle if exception message changes + // if (e.getMessage().equals("Address already in use: NET_Bind")) + if (ioe instanceof java.net.BindException) + System.err.println("*** Be sure to stop any other running instances of programs using this port!"); + } + } +} \ No newline at end of file diff --git a/assignments/src/MV3500Cohort2024JulySeptember/homework2/Romero/README.md b/assignments/src/MV3500Cohort2024JulySeptember/homework2/Romero/README.md new file mode 100644 index 0000000000..c51055becc --- /dev/null +++ b/assignments/src/MV3500Cohort2024JulySeptember/homework2/Romero/README.md @@ -0,0 +1,7 @@ +# Rene Romero Homework 2 + +*** + +## Description + + diff --git a/assignments/src/MV3500Cohort2024JulySeptember/homework2/Romero/RomeroServerHW2.java b/assignments/src/MV3500Cohort2024JulySeptember/homework2/Romero/RomeroServerHW2.java new file mode 100644 index 0000000000..43c3c77459 --- /dev/null +++ b/assignments/src/MV3500Cohort2024JulySeptember/homework2/Romero/RomeroServerHW2.java @@ -0,0 +1,75 @@ +package MV3500Cohort2024JulySeptember.homework2.Romero; + +import java.io.IOException; +import java.net.*; + +/** + * This server program works a bit differently by creating and dispatching a + * new thread to handle multiple incoming socket connections, one after another, all running in parallel. + * This advanced technique is often used in high=performance high=capacity server programs. + * + * @see TcpExample4Client + * @see TcpExample4HandlerThread + * + * @see <a href="../../../src/TcpExamples/TcpExample4TerminalLog.txt" target="blank">TcpExample4TerminalLog.txt</a> + * @see <a href="../../../src/TcpExamples/TcpExample4SequenceDiagram.png" target="blank">TcpExample4SequenceDiagram.png</a> + * @see <a href="../../../src/TcpExamples/TcpExample4SequenceSketch.png" target="blank">TcpExample4SequenceSketch.png</a> + * + * @author Don McGregor + * @author Don Brutzman + * @author MV3500 class + */ +public class RomeroServerHW2 +{ + /** Default constructor */ + public RomeroServerHW2() + { + // default constructor + } + /** + * Program invocation, execution starts here + * @param args command-line arguments + */ + public static void main(String[] args) + { + try { + ServerSocket serverSocket = new ServerSocket(2317); + Socket clientConnectionSocket; + TcpExample4HandlerThread handlerThread; + + int connectionCount = 0; // state variable + + System.out.println(RomeroServerHW2.class.getName() + " ready to accept socket connections..."); + while (true) // infinite loop + { + clientConnectionSocket = serverSocket.accept(); // block! until connected + + connectionCount++; // unblocked, got another connection + + // TODO option for the student, provide initial message *to the client* + // that we are handing off to a dispatch thread... because that is polite behavior. + // Plenty of code in Example3, we instead let our proxy thread + // TcpExample4HandlerThread introduce itself to the client. + + System.out.println("============================================================="); + System.out.println(RomeroServerHW2.class.getName() + ".handlerThread created for connection #" + connectionCount + "..."); + + // hand off this aready-created and connected socket to constructor + handlerThread = new TcpExample4HandlerThread(clientConnectionSocket); + handlerThread.start();// invokes the run() method in that object + System.out.println(RomeroServerHW2.class.getName() + ".handlerThread is now dispatched and running, using most recent connection..."); + + // while(true) continue looping, serverSocket is still waiting for another customer client + } + } + catch (IOException e) { + System.out.println("Problem with " + RomeroServerHW2.class.getName() + " networking:"); // describe what is happening + System.out.println("Error: " + e); + // Provide more helpful information to user if exception occurs due to running twice at one time + if (e instanceof java.net.BindException) { + System.out.println("*** Be sure to stop any other running instances of programs using this port!"); + } + } + System.out.println("============================================================="); // execution complete + } +} diff --git a/assignments/src/MV3500Cohort2024JulySeptember/homework2/Romero/TcpExample4Client.java b/assignments/src/MV3500Cohort2024JulySeptember/homework2/Romero/TcpExample4Client.java new file mode 100644 index 0000000000..7b64e47eab --- /dev/null +++ b/assignments/src/MV3500Cohort2024JulySeptember/homework2/Romero/TcpExample4Client.java @@ -0,0 +1,84 @@ +package MV3500Cohort2024JulySeptember.homework2.Romero; + +import java.io.*; +import java.net.*; +//import java.time.LocalTime; // conversion? + +/** + * This client program establishes a socket connection to the {@link TcpExample4DispatchServer}, + * then checks how long it takes to read the single line it expects as a server response. + * No fancy footwork here, it is pretty simple and similar to {@link TcpExample3Client}. + * + * @see TcpExample4DispatchServer + * @see TcpExample4HandlerThread + * + * @see <a href="../../../src/TcpExamples/TcpExample4TerminalLog.txt" target="blank">TcpExample4TerminalLog.txt</a> + * @see <a href="../../../src/TcpExamples/TcpExample4SequenceDiagram.png" target="blank">TcpExample4SequenceDiagram.png</a> + * @see <a href="../../../src/TcpExamples/TcpExample4SequenceSketch.png" target="blank">TcpExample4SequenceSketch.png</a> + * + * @author Don McGregor + * @author Don Brutzman + * @author MV3500 class + */ +public class TcpExample4Client +{ + /** Default constructor */ + public TcpExample4Client() + { + // default constructor + } + static String DESTINATION_HOST = "localhost"; + static int MAX_LOOP_COUNT = 4; + + /** + * Program invocation, execution starts here + * @param args command-line arguments + */ + public static void main(String[] args) { + try { + System.out.println(TcpExample4Client.class.getName() + " start, loop " + MAX_LOOP_COUNT + " times"); + System.out.println("======================================================="); + for (int loopCount = 1; loopCount <= MAX_LOOP_COUNT; loopCount++) // loop then exit + { + System.out.println(TcpExample4Client.class.getName() + " creating new socket #" + loopCount + "..."); + + // We request an IP to connect to ("localhost") and + // port number at that IP (2317). This establishes + // a connection to that IP in the form of the Socket + // object; the server uses a ServerSocket to wait for + // connections.This particualar example is interacting + // with what it expects is a server that writes a single text + // line after 10 sec. + long startTime = System.currentTimeMillis(); + + // open a socket for each loop + Socket socket = new Socket(DESTINATION_HOST, 2317); + + // Setup. Read the single line written by the server. + // We'd do things a bit differently if many lines to be read + // from the server, instead of one only. + InputStream is = socket.getInputStream(); + Reader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + + String serverMessage = br.readLine(); // blocks + long readTime = System.currentTimeMillis(); + long timeLength = readTime - startTime; + + System.out.println(TcpExample4Client.class.getName() + ": message received from server='" + serverMessage + "'"); + System.out.println(TcpExample4Client.class.getName() + ": time msec required for read=" + timeLength); + System.out.println("======================================================="); + // To push this further, launch multiple copies of TcpExample4Client simultaneously + } + System.out.println(TcpExample4Client.class.getName() + " complete"); + // main method now exits + } catch (IOException e) { + System.out.println("Problem with " + TcpExample4Client.class.getName() + " networking:networking:"); // describe what is happening + System.out.println("Error: " + e); + // Provide more helpful information to user if exception occurs due to running twice at one time + if (e instanceof java.net.BindException) { + System.out.println("*** Be sure to stop any other running instances of programs using this port!"); + } + } + } +} diff --git a/assignments/src/MV3500Cohort2024JulySeptember/homework2/Romero/TcpExample4HandlerThread.java b/assignments/src/MV3500Cohort2024JulySeptember/homework2/Romero/TcpExample4HandlerThread.java new file mode 100644 index 0000000000..70bc2c165e --- /dev/null +++ b/assignments/src/MV3500Cohort2024JulySeptember/homework2/Romero/TcpExample4HandlerThread.java @@ -0,0 +1,91 @@ +package MV3500Cohort2024JulySeptember.homework2.Romero; + +import java.io.*; +import java.net.*; + +/** + * <p> + * This utility class supports the {@link TcpExample4DispatchServer} program, + * handling all programming logic needed for a new socket connection + * to run in a thread of its own. This is the server + * portion as well, so we artificially invent what happens + * if the server can't respond to a connection for several seconds. + * </p> + * <p> + * Warning: do not run this class! It is created and used automatically by {@link TcpExample4DispatchServer} at run time. + * </p> + * + * @see TcpExample4Client + * @see TcpExample4DispatchServer + * + * @see <a href="../../../src/TcpExamples/TcpExample4TerminalLog.txt" target="blank">TcpExample4TerminalLog.txt</a> + * @see <a href="../../../src/TcpExamples/TcpExample4SequenceDiagram.png" target="blank">TcpExample4SequenceDiagram.png</a> + * @see <a href="../../../src/TcpExamples/TcpExample4SequenceSketch.png" target="blank">TcpExample4SequenceSketch.png</a> + * + * @author Don McGregor + * @author Don Brutzman + * @author MV3500 class + */ +public class TcpExample4HandlerThread extends Thread +{ + /** The socket connection to a client */ + Socket socket; + + /** + * The thread constructor creates the socket from a ServerSocket, waiting for the client to connect, + * and passes that socket when constructing the thread responsible for handling the connection. + * + * @param socket The socket connection handled by this thread + */ + TcpExample4HandlerThread(Socket socket) + { + this.socket = socket; + } + /** + * Program invocation and execution starts here - but is illegal and unwanted, so warn the unsuspecting user! + * @param args command-line arguments + */ + public static void main(String[] args) + { + System.out.println ("*** TcpExample4HandlerThread is not a standalone executable progam."); + System.out.println ("*** Please run TcpExample4DispatchServer instead... now exiting."); + } + + /** Handles one connection. We add an artificial slowness + * to handling the connection with a sleep(). This means + * the client won't see a server connection response for ten seconds (default). + */ + // @overriding run() method in Java Thread class is deliberate + @Override + public void run() + { + try + { + System.out.println(TcpExample4HandlerThread.class.getName() + " starting to handle a thread..."); + + // get the connection output stream, then wait a period of time. + OutputStream os = socket.getOutputStream(); + PrintStream ps = new PrintStream(os); + + final long TIMEOUT = 2000; // 2000 milliseconds = 2 seconds, 10000 milliseconds = 10 seconds + System.out.println(TcpExample4HandlerThread.class.getName() + " pausing for TIMEOUT=" + TIMEOUT + "ms" + + " to emulate computation and avoid server-side overload"); + Thread.sleep(TIMEOUT); + + // ps is the PrintStream is the Java way to use System.print() to pass data along the socket. + ps.println("This message was written by the server " + TcpExample4HandlerThread.class.getName()); // TODO insert socket count here! + ps.flush(); // make sure that it indeed escapes current process and reaches the client + socket.close(); // all clear, no longer need socket + System.out.println(TcpExample4HandlerThread.class.getName() + " finished handling a thread, now exit."); + } + catch(IOException | InterruptedException e) // either a networking or a threading problem + { + System.out.println("Problem with " + TcpExample4HandlerThread.class.getName() + " networking:"); // describe what is happening + System.out.println("Error: " + e); + + // Provide more helpful information to user if exception occurs due to running twice at one time + if (e instanceof java.net.BindException) + System.out.println("*** Be sure to stop any other running instances of programs using this port!"); + } + } +} -- GitLab