Skip to content
Snippets Groups Projects
Commit f044fd76 authored by rojas's avatar rojas
Browse files

Update

parent 1845e664
No related branches found
No related tags found
No related merge requests found
......@@ -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 dayreference: <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 dar 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
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>
* <p>
* Warning: do not run this class! It is created and used automatically by {@link TcpExample4DispatchServer} at run time.
* </p>
*
*
* @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!");
}
}
}
assignments/src/MV3500Cohort2024JulySeptember/homework2/Romero/images/MOTD.png

12.9 KiB

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