Skip to content
Snippets Groups Projects
Commit 2a7cbd7d authored by Terry D. Norbraten's avatar Terry D. Norbraten
Browse files

Merge origin/master

parents ed8b4921 f690c26a
No related branches found
No related tags found
No related merge requests found
Showing
with 712 additions and 110 deletions
......@@ -4,14 +4,28 @@ import java.io.*;
import java.net.*;
import java.util.Scanner;
/**
* Client constructor
*/
public class HomeworkClient {
/**
* Client constructor
*/
public HomeworkClient() {
// default constructor
}
/**
* local host
*/
public final static String LOCALHOST = "0:0:0:0:0:0:0:1";
public static void main(String[] args) {
/**
* Client constructor
* @param args passed in args
*/
public static void main(String[] args) {
Socket socket = null;
InputStream is;
Reader isr;
......@@ -19,7 +33,7 @@ public class HomeworkClient {
PrintWriter pw;
String serverMessage;
int clientLoopCount = 0;
Scanner scanner = new Scanner(System.in);
try {
......@@ -42,26 +56,28 @@ public class HomeworkClient {
serverMessage = br.readLine();
System.out.println("==================================================");
System.out.print("Client loop " + clientLoopCount + ": ");
System.out.println("now we're talking!");
System.out.println("The message the server sent was: '" + serverMessage + "'");
Thread.sleep(500l);
}
} catch (IOException | InterruptedException e) {
System.err.println("Problem with " + HomeworkClient.class.getName() + " networking:");
System.err.println("Error: " + e);
if (e instanceof java.net.BindException) {
System.err.println("*** Be sure to stop any other running instances of programs using this port!");
}
} finally {
try {
if (socket != null)
if (socket != null) {
socket.close();
} catch (IOException e) {}
}
} catch (IOException e) {
}
System.out.println();
System.out.println(HomeworkClient.class.getName() + " exit");
}
......
package MV3500Cohort2024JulySeptember.homework1.Smith;
import java.io.*;
import java.net.*;
/**
* Sever constructor
*/
public class HomeworkServer {
private static int runningTotal = 0; // Initialize running total
/**
* Sever constructor
*/
public HomeworkServer() {
// default constructor
}
/**
* main
* @param args passed in args
*/
public static void main(String[] args) {
try {
System.out.println(HomeworkServer.class.getName() + " has started...");
......@@ -31,13 +41,13 @@ public class HomeworkServer {
// Read the number sent by the client
BufferedReader br = new BufferedReader(new InputStreamReader(clientConnectionSocket.getInputStream()));
int clientNumber = Integer.parseInt(br.readLine());
// Update the running total
int clientNumnerSqr = clientNumber * clientNumber;
runningTotal += clientNumber;
// Send back the updated total
ps.println("Client sent: " + clientNumber + ", client number squared was: "+ clientNumnerSqr+", Running total: " + runningTotal);
ps.println("Client sent: " + clientNumber + ", client number squared was: " + clientNumnerSqr + ", Running total: " + runningTotal);
System.out.println("Client sent: " + clientNumber + ", Running total: " + runningTotal);
localAddress = clientConnectionSocket.getLocalAddress();
......@@ -47,13 +57,14 @@ public class HomeworkServer {
System.out.print("Server loop " + serverLoopCount + ": ");
System.out.println(HomeworkServer.class.getName() + " socket pair showing host name, address, port:");
System.out.println(" (( " +
localAddress.getHostName() + "=" + localAddress.getHostAddress() + ", " + localPort + " ), ( " +
remoteAddress.getHostName() + "=" + remoteAddress.getHostAddress() + ", " + remotePort + " ))");
if (localAddress.getHostName().equals(localAddress.getHostAddress()) ||
remoteAddress.getHostName().equals(remoteAddress.getHostAddress()))
System.out.println(" note HostName matches address if host has no DNS name");
System.out.println(" (( "
+ localAddress.getHostName() + "=" + localAddress.getHostAddress() + ", " + localPort + " ), ( "
+ remoteAddress.getHostName() + "=" + remoteAddress.getHostAddress() + ", " + remotePort + " ))");
if (localAddress.getHostName().equals(localAddress.getHostAddress())
|| remoteAddress.getHostName().equals(remoteAddress.getHostAddress())) {
System.out.println(" note HostName matches address if host has no DNS name");
}
ps.flush();
}
}
......@@ -66,4 +77,3 @@ public class HomeworkServer {
}
}
}
/**
* TCP Unicast homework assignments supporting the NPS MOVES MV3500 Networked Graphics course.
*
* @see <a href="https://gitlab.nps.edu/Savage/NetworkedGraphicsMV3500/-/tree/master/assignments" target="_blank">networkedGraphicsMV3500 assignments</a>
* @see java.lang.Package
* @see <a href="https://stackoverflow.com/questions/22095487/why-is-package-info-java-useful" target="_blank">StackOverflow: why-is-package-info-java-useful</a>
* @see <a href="https://stackoverflow.com/questions/624422/how-do-i-document-packages-in-java" target="_blank">StackOverflow: how-do-i-document-packages-in-java</a>
*/
package MV3500Cohort2024JulySeptember.homework1.Smith;
......@@ -6,10 +6,56 @@ import java.net.InetAddress;
import java.util.Scanner;
/**
*
* @author Jack
* <p>
* The simplest TCP network program, opening a socket between a client and server
* and send a message from the client to the server.
* It listens for any socket connection response, either from telnet (telnet localhost 2317)
* or another client program.
* Once a socket connection is established, the client sends messages to the
* server and the server echos the message back to the client.
*
* <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>
* Notice that "Client Received" matches
* what is written by the code below, over the output stream.
* </p>
* * <p>
* Notice that "Server Received" matches the string sent by the client.
* </p>
* <p>
* After the echoed message is received by the client, the program exits.
* For example:
* Enter message to send to server: hello
* Client received: Hello From Server, I received: hello
* [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
* @author james.timberlake@nps.edu
*/
public class Client {
/**
* Default constructor
* Program invocation, execution starts here
* @param args command-line arguments
*/
public static void main(String[] args) {
DatagramSocket socket = null;
Scanner scanner = new Scanner(System.in);
......
......@@ -5,10 +5,56 @@ import java.net.DatagramSocket;
import java.net.InetAddress;
/**
*
* @author Jack
* <p>
* The simplest TCP network program, opening a socket between a client and server
* and send a message from the client to the server.
* It listens for any socket connection response, either from telnet (telnet localhost 2317)
* or another client program.
* Once a socket connection is established, the client sends messages to the
* server and the server echos the message back to the client.
*
* <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>
* Notice that "Client Received" matches
* what is written by the code below, over the output stream.
* </p>
* * <p>
* Notice that "Server Received" matches the string sent by the client.
* </p>
* <p>
* After the echoed message is received by the client, the program exits.
* For example:
* Enter message to send to server: hello
* Client received: Hello From Server, I received: hello
* [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
* @author james.timberlake@nps.edu
*/
public class Server {
/**
* Default constructor
* Program invocation, execution starts here
* @param args none
*/
public static void main(String[] args) {
DatagramSocket socket = null;
......
/**
* TCP Unicast homework assignments supporting the NPS MOVES MV3500 Networked Graphics course.
*
* @see <a href="https://gitlab.nps.edu/Savage/NetworkedGraphicsMV3500/-/tree/master/assignments" target="_blank">networkedGraphicsMV3500 assignments</a>
* @see java.lang.Package
* @see <a href="https://stackoverflow.com/questions/22095487/why-is-package-info-java-useful" target="_blank">StackOverflow: why-is-package-info-java-useful</a>
* @see <a href="https://stackoverflow.com/questions/624422/how-do-i-document-packages-in-java" target="_blank">StackOverflow: how-do-i-document-packages-in-java</a>
*/
package MV3500Cohort2024JulySeptember.homework1.Timberlake;
/**
* TCP Unicast homework assignments supporting the NPS MOVES MV3500 Networked Graphics course.
*
* @see <a href="https://gitlab.nps.edu/Savage/NetworkedGraphicsMV3500/-/tree/master/assignments" target="_blank">networkedGraphicsMV3500 assignments</a>
* @see java.lang.Package
* @see <a href="https://stackoverflow.com/questions/22095487/why-is-package-info-java-useful" target="_blank">StackOverflow: why-is-package-info-java-useful</a>
* @see <a href="https://stackoverflow.com/questions/624422/how-do-i-document-packages-in-java" target="_blank">StackOverflow: how-do-i-document-packages-in-java</a>
*/
package MV3500Cohort2024JulySeptember.homework1.Williams;
package MV3500Cohort2024JulySeptember.homework2.Matiski;
import java.io.*;
import java.net.*;
/**
* This client program establishes a socket connection to the {@link TcpExamples.TcpExample4DispatchServer},
* then checks how long it takes to read the single line it expects as a server response.
* The modification I have added is it checks for a password from the server. And it matches it says success and disconnects
* No fancy footwork here, it is pretty simple and similar to {@link TcpExamples.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>
* credit to the following for providing the class example that I modified
* @author Don McGregor
* @author Don Brutzman
* @author MV3500 class
* @MarkMM
*/
public class Matiski2Client
{
/** Default constructor */
public Matiski2Client()
{
// 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(Matiski2Client.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(Matiski2Client.class.getName() + " creating new socket #" + loopCount + "...");
long startTime = System.currentTimeMillis();
// Open a socket for each loop
Socket socket = new Socket(DESTINATION_HOST, 2317);
// Note our local port on this client host is not specified - because
// that doesn't matter. It is an "ephemeral" port on localhost.
// Setup. Read the prompt from the server.
InputStream is = socket.getInputStream();
Reader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
PrintStream ps = new PrintStream(os);
// Read server prompt for password
String serverPrompt = br.readLine();
System.out.println(serverPrompt); // Should print "Enter password:"
// Send the password
String password = "Mark"; // Replace with your password
ps.println(password);
ps.flush();
// Read server response
String serverResponse = br.readLine();
System.out.println(serverResponse);
if ("Password accepted. Processing your request...".equals(serverResponse)) {
// Read the actual message from the server
String serverMessage = br.readLine();
long readTime = System.currentTimeMillis();
long timeLength = readTime - startTime;
System.out.println(Matiski2Client.class.getName() + ": message received from server='" + serverMessage + "'");
System.out.println(Matiski2Client.class.getName() + ": time msec required for read=" + timeLength);
}
System.out.println("=======================================================");
socket.close(); // Close the socket after the interaction
}
System.out.println(Matiski2Client.class.getName() + " complete");
// main method now exits
} catch (IOException e) {
System.out.println("Problem with " + Matiski2Client.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!");
}
else if (e instanceof java.net.ConnectException)
{
System.out.println("*** Be sure to start the server before starting the client!");
}
}
}
}
\ No newline at end of file
package MV3500Cohort2024JulySeptember.homework2.Romero;
package MV3500Cohort2024JulySeptember.homework2.Matiski;
import java.io.*;
import java.net.*;
/**
* <p>
* This utility class supports the {@link RomeroServerHW2} program,
* This utility class supports the {@link TcpExamples.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.
* Warning: do not run this class! It is created and used automatically by {@link TcpExamples.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>
......@@ -24,7 +26,7 @@ import java.net.*;
* @author Don Brutzman
* @author MV3500 class
*/
public class TcpExample4HandlerThread extends Thread
public class Matiski2HandlerThread extends Thread
{
/** The socket connection to a client */
Socket socket;
......@@ -35,7 +37,7 @@ public class TcpExample4HandlerThread extends Thread
*
* @param socket The socket connection handled by this thread
*/
TcpExample4HandlerThread(Socket socket)
Matiski2HandlerThread(Socket socket)
{
this.socket = socket;
}
......@@ -54,36 +56,65 @@ public class TcpExample4HandlerThread extends Thread
* 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()
@Override
public void run()
{
try
{
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);
System.out.println(Matiski2HandlerThread.class.getName() + " starting to handle a thread...");
// Set up input and output streams for communication
InputStream is = socket.getInputStream();
Reader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
PrintStream ps = new PrintStream(os);
// Ask for password
final String correctPassword = "Mark";
ps.println("Enter password:");
ps.flush();
final long TIMEOUT = 2000; // 2000 milliseconds = 2 seconds, 10000 milliseconds = 10 seconds
System.out.println(TcpExample4HandlerThread.class.getName() + " pausing for TIMEOUT=" + TIMEOUT + "ms" +
String clientPassword = br.readLine(); // Read the password sent by the client
boolean isPasswordCorrect = correctPassword.equals(clientPassword);
if (isPasswordCorrect) {
ps.println("Password accepted. Processing your request...");
ps.flush();
final long TIMEOUT = 2000; // 2000 milliseconds = 2 seconds
System.out.println(Matiski2HandlerThread.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.");
// Continue with the original logic
ps.println("This message was written by the server " + Matiski2HandlerThread.class.getName());
ps.flush();
} else {
ps.println("Incorrect password. Connection will be terminated.");
ps.flush();
}
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!");
// Inform the client that the connection will be closed
if (isPasswordCorrect) {
ps.println("Your request has been processed. The connection will now be closed.");
} else {
ps.println("Due to incorrect password, the connection will be closed.");
}
ps.flush();
socket.close(); // Close the socket after handling the connection
System.out.println(Matiski2HandlerThread.class.getName() + " finished handling a thread, now exit.");
}
catch(IOException | InterruptedException e)
{
System.out.println("Problem with " + Matiski2HandlerThread.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!");
}
}
}
package MV3500Cohort2024JulySeptember.homework2.Matiski;
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 Matiski2HandlerThread
*
* @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 Matiski2Server
{
/** Default constructor */
public Matiski2Server()
{
// default constructor
}
/**
* Program invocation, execution starts here
* @param args command-line arguments
*/
public static void main(String[] args)
{
try {
ServerSocket serverSocket = new ServerSocket(2317);
Matiski2HandlerThread handlerThread;
Socket clientConnection;
int connectionCount = 0; // state variable
System.out.println(Matiski2Server.class.getName() + " ready to accept socket connections...");
while (true) // infinite loop
{
clientConnection = serverSocket.accept(); // block until connected
connectionCount++; // unblocked, got another connection
System.out.println("=============================================================");
System.out.println(Matiski2Server.class.getName() + ".handlerThread invocation for connection #" + connectionCount + "...");
handlerThread = new Matiski2HandlerThread(clientConnection);
handlerThread.start(); // invokes the run() method in that object
System.out.println(Matiski2Server.class.getName() + ".handlerThread is launched, awaiting another connection...");
}
} catch (IOException e) {
System.out.println("Problem with " + Matiski2Server.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("=============================================================");
}
}
# Mark Matiski Homework2
***
## Description
Modification to TCPExample4 to ask for a password
Closes once password is entered correctly or incorrectly.
Biggest changes are in the handler thread.
/**
* TCP Unicast homework assignments supporting the NPS MOVES MV3500 Networked Graphics course.
*
* @see <a href="https://gitlab.nps.edu/Savage/NetworkedGraphicsMV3500/-/tree/master/assignments" target="_blank">networkedGraphicsMV3500 assignments</a>
* @see java.lang.Package
* @see <a href="https://stackoverflow.com/questions/22095487/why-is-package-info-java-useful" target="_blank">StackOverflow: why-is-package-info-java-useful</a>
* @see <a href="https://stackoverflow.com/questions/624422/how-do-i-document-packages-in-java" target="_blank">StackOverflow: how-do-i-document-packages-in-java</a>
*/
package MV3500Cohort2024JulySeptember.homework2.Matiski;
......@@ -8,12 +8,12 @@ Modification to TCPExample4 to show the Message of the day (MOTD), depending on
The server side sets up a server listening for incoming connectios.
When a client attempts a connection to the server it sends the day of the week for the current connection.
When a client attempts a connection to the server, it sends the day of the week for the current connection, based on the client's day.
Once received the day of the week, the server reply with a message according to the day of the week.
Phrases taken from
https://www.divein.com/everyday/monday-motivation-quotes/
Phrases taken from: <b>https://www.divein.com/everyday/monday-motivation-quotes/</b>
<a href="images/MOTD.png"><img src="images/MOTD.png" width="700" align="center"/></a>
Message of the day reference: <b>https://en.wikipedia.org/wiki/Message_of_the_day </b>
......@@ -11,24 +11,16 @@ import java.time.DayOfWeek;
* 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 RomeroClientHW2
{
/** Default constructor */
public RomeroClientHW2()
{
// default constructor
}
/**
* Default constructor
*/
public RomeroClientHW2() { }
/**
* Program invocation, execution starts here
......@@ -36,12 +28,22 @@ public class RomeroClientHW2
*/
public static void main(String[] args) {
/**
* Using DataInputStream and DataOutputStream to convert bytes from an
* input stream and converting then into Java's primitive data and vice versa
* respectively *
*/
DataInputStream in;
DataOutputStream out;
/**
* Getting the current date from the client, and getting the
* specific day of the week.
*/
LocalDate currentDate = LocalDate.now();
DayOfWeek day = currentDate.getDayOfWeek();
//Cheching the day of the week obtined
System.out.println("Current date: " + currentDate);
System.out.println("Today is: " + day + "\n");
......@@ -49,15 +51,27 @@ public class RomeroClientHW2
try {
Socket clientConnectionSocket = new Socket("localhost", 2317);
/**
* Creating a DataInputStream and DataOutputStream objects that reads data
* from the input stream of the socket connection and writes data through
* a socket connection, accordingly
*/
in = new DataInputStream(clientConnectionSocket.getInputStream());
out = new DataOutputStream(clientConnectionSocket.getOutputStream());
//Specifying the daY of the week, in string format
out.writeUTF(day.name());
String mensaje = in.readUTF();
System.out.println(mensaje);
/**
* Reading and printing strings from the server:
* message1 reads the number of client
* message2 reads the MOTD
*/
String message1 = in.readUTF();
String message2 = in.readUTF();
System.out.println(message1);
System.out.println(message2);
clientConnectionSocket.close();
......@@ -70,4 +84,4 @@ public class RomeroClientHW2
}
}
}
}
}
\ No newline at end of file
package MV3500Cohort2024JulySeptember.homework2.Romero;
import java.io.*;
import java.net.*;
/**
* <p>
* This utility class supports the {@link RomeroServerHW2} 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>
*
* @author Don Brutzman
* @author MV3500 class
* @author Rene
*/
public class RomeroHandlerThreadHW2 extends Thread
{
private final Socket clientConnectionSocket;
/**
* 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
*/
RomeroHandlerThreadHW2(Socket clientConnectionSocket)
{
this.clientConnectionSocket = clientConnectionSocket;
}
/**
* 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 ("*** Please run RomeroServerHW2 instead.");
}
/** Handles one connection
* @overriding run() method in Java Thread class is deliberate
*/
@Override
public void run()
{
/**
* Using DataInputStream and DataOutputStream to convert bytes from an
* input stream and converting then into Java's primitive data and vice versa
* respectively *
*/
DataInputStream in;
DataOutputStream out;
try
{
System.out.println(RomeroHandlerThreadHW2.class.getName() + " starting to handle a thread...");
/**
* Creating a DataInputStream and DataOutputStream objects that reads data
* from the input stream of the socket connection and writes data through
* a socket connection, accordingly
*/
in = new DataInputStream(clientConnectionSocket.getInputStream());
out = new DataOutputStream(clientConnectionSocket.getOutputStream());
//Reading the day of the day from client
String messageFromClient = in.readUTF();
//Displaying in server side the day sended by the user
System.out.println("\nClient connected on: " + messageFromClient);
/**
* Displaying a message of the day or welcome message when a user first connects
* to the server. The approach is the first step after creating the socket
* between client - server.
*/
String messageOTD = "";
switch(messageFromClient) {
case "MONDAY" -> messageOTD = "\n\"Mondays are the start of the work week which offer new beginnings 52 times a year!\"\n \t- David Dweck";
case "TUESDAY" -> messageOTD = "\n\"May your Tuesday be like your coffee: strong, smooth, and full of warmth.\"\n \t- Unknown";
case "WEDNESDAY" -> messageOTD = "\n\"Wednesdays will always bring smiles for the second half of the week.\"\n \t- Anthony T. Hincks";
case "THURSDAY" -> messageOTD = "\n\"Thursday is a day to admit your mistakes and try to improve.\"\n \t- Byron Pulsifer";
case "FRIDAY" -> messageOTD = "\n\"Every Friday, I like to high five myself for getting through another week\non little more than caffeine, willpower, and inappropriate humor.\"\n \t- Anonymous";
case "SATURDAY" -> messageOTD = "\n\"Saturday is a time to enjoy the small things in life, and to look back on the week with gratitude.\"\n \t- Unknown";
case "SUNDAY" -> messageOTD = "\n\"Sunday clears away the rust of the whole week.\"\n \t- Joseph Addison";
default -> messageOTD = "\nError while getting the day of the week";
}
//Writing the MOTD to the client, according to its local day
out.writeUTF("\n**********************************************************************\n"
+ messageOTD +
"\n\n**********************************************************************\n");
out.flush(); // make sure that it indeed escapes current process and reaches the client
clientConnectionSocket.close(); // all clear, no longer need socket
System.out.println(RomeroHandlerThreadHW2.class.getName() + " finished handling a thread, now exit.");
}
catch(IOException e) // either a networking or a threading problem
{
System.out.println("Problem with " + RomeroHandlerThreadHW2.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!");
}
}
}
\ No newline at end of file
package MV3500Cohort2024JulySeptember.homework2.Romero;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;
......@@ -9,86 +8,55 @@ 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
* @author Rene
*/
public class RomeroServerHW2
{
/** Default constructor */
public RomeroServerHW2()
{
// default constructor
}
/**
* Default constructor
*/
public RomeroServerHW2() { }
/**
* Program invocation, execution starts here
* @param args command-line arguments
*/
public static void main(String[] args)
{
DataInputStream in;
DataOutputStream out;
{
try {
ServerSocket serverSocket = new ServerSocket(2317);
ServerSocket serverSocket = new ServerSocket(2317);
System.out.println("\nServer has been initializated ... ");
System.out.println("\nWaiting for conections ...\n");
RomeroHandlerThreadHW2 handlerThread;
Socket clientConnectionSocket;
System.out.println("Server has been initializated ... ");
System.out.println("Witing for conections ...");
//Counting the number of connections
int connectionCount = 0;
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
in = new DataInputStream(clientConnectionSocket.getInputStream());
out = new DataOutputStream(clientConnectionSocket.getOutputStream());
String messageFromClient = in.readUTF();
System.out.println("Client connected on: " + messageFromClient);
String messageOTD = "";
switch(messageFromClient) {
case "MONDAY" -> messageOTD = "\n\"Mondays are the start of the work week which offer new beginnings 52 times a year!\"\n \t- David Dweck";
case "TUESDAY" -> messageOTD = "\n\"May your Tuesday be like your coffee: strong, smooth, and full of warmth.\"\n \t- Unknown";
case "WEDNESDAY" -> messageOTD = "\n\"Wednesdays will always bring smiles for the second half of the week.\"\n \t- Anthony T. Hincks";
case "THURSDAY" -> messageOTD = "\n\"Thursday is a day to admit your mistakes and try to improve.\"\n \t- Byron Pulsifer";
case "FRIDAY" -> messageOTD = "\n\"Every Friday, I like to high five myself for getting through another week\non little more than caffeine, willpower, and inappropriate humor.\"\n \t- Anonymous";
case "SATURDAY" -> messageOTD = "\n\"Saturday is a time to enjoy the small things in life, and to look back on the week with gratitude.\"\n \t- Unknown";
case "SUNDAY" -> messageOTD = "\n\"Sunday clears away the rust of the whole week.\"\n \t- Joseph Addison";
default -> messageOTD = "\nError while getting the day of the week";
}
out.writeUTF("\n**********************************************************************\n"
+ messageOTD +
"\n\n**********************************************************************\n\n"
+ "You are the client numer: " + connectionCount);
System.out.println("=============================================================");
System.out.println(RomeroServerHW2.class.getName() + ".handlerThread created for connection #" + connectionCount + "...");
connectionCount++;
//printing clientConnectionSocket object
System.out.println(clientConnectionSocket);
// 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...");
//Sending to the user the client number, based on arrival
DataOutputStream outServer = new DataOutputStream(clientConnectionSocket.getOutputStream());
outServer.writeUTF("\nYou are the client numer: " + connectionCount);
// while(true) continue looping, serverSocket is still waiting for another customer client
//Thread handler
handlerThread = new RomeroHandlerThreadHW2(clientConnectionSocket);
Thread thread = new Thread(handlerThread);
thread.start();
System.out.println(RomeroHandlerThreadHW2.class.getName() + ".handlerThread is launched, awaiting another connection...");
}
}
catch (IOException e) {
......@@ -101,4 +69,4 @@ public class RomeroServerHW2
}
System.out.println("============================================================="); // execution complete
}
}
}
\ No newline at end of file
assignments/src/MV3500Cohort2024JulySeptember/homework2/Romero/images/MOTD.png

12.9 KiB

package MV3500Cohort2024JulySeptember.homework2.Smith;
/**
* This the the rock paper sciccors client.
* @author tjsus
*/
import java.io.*;
import java.net.*;
import java.util.Scanner;
/**
* Client Class
* @author tjsus
*/
public class Client {
/**
* Client constructor
*/
public Client() {
// default constructor
}
/**
* local host
*/
public final static String LOCALHOST = "0:0:0:0:0:0:0:1";
/**
* Main
* @param args passed in args
*/
public static void main(String[] args) {
Socket socket = null;
InputStream is;
......
# Smith Homework 2
***
## Description
Modification of TcpExample3 and adding some code to implement a rock, paper, sciccors game with a client.
The 'Server' class sets up a server that listens for incoming client connections.
The 'Client' class connects to a server running on localhost. It sends user input from the console to the server and displays messages received from the server.
\ No newline at end of file
package MV3500Cohort2024JulySeptember.homework2.Smith;
/**
* This the the rock paper sciccors server.
* @author tjsus
*/
import java.io.*;
import java.net.*;
import java.util.Random;
/**
* Client Class
* @author tjsus
*/
public class Server {
private static int runningTotal = 0; // Initialize running total
/**
* Server constructor
*/
public Server() {
// default constructor
}
/**
* Main
* @param args passed in args
*/
public static void main(String[] args) {
try {
System.out.println(Server.class.getName() + " has started...");
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment