Skip to content
Snippets Groups Projects
Commit 60927a08 authored by tjsus's avatar tjsus
Browse files

Assignment 2

parent 436b0320
No related branches found
No related tags found
No related merge requests found
Showing
with 136 additions and 794 deletions
package MV3500Cohort2024JulySeptember.homework1.Romero;
public class Homework {
public static void main(String args[]) {
System.out.println("Hello world!");
}
}
\ No newline at end of file
...@@ -8,8 +8,7 @@ import java.net.ServerSocket; ...@@ -8,8 +8,7 @@ import java.net.ServerSocket;
import java.net.Socket; import java.net.Socket;
/** /**
* Homework1: Open a socket and waiting for a client to connect to the socket. *
*
* @author simonschnitzler * @author simonschnitzler
*/ */
public class SchnitzlerUnicastNetworking { public class SchnitzlerUnicastNetworking {
......
...@@ -12,7 +12,6 @@ import java.util.Scanner; ...@@ -12,7 +12,6 @@ import java.util.Scanner;
* @author tbavlsik * @author tbavlsik
*/ */
public class BavlsikClient { public class BavlsikClient {
public final static String LOCALHOST = "0:0:0:0:0:0:0:1"; //Local host public final static String LOCALHOST = "0:0:0:0:0:0:0:1"; //Local host
/** /**
...@@ -22,36 +21,19 @@ public class BavlsikClient { ...@@ -22,36 +21,19 @@ public class BavlsikClient {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
Socket socket = new Socket(LOCALHOST, 2317); Socket socket = new Socket(LOCALHOST, 2317);
Thread readerThread = new Thread(new Reader(socket)); new Thread(new Reader(socket)).start();
readerThread.start();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Scanner scanner = new Scanner(System.in); Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) { while (scanner.hasNextLine()) {
String msg = scanner.nextLine(); out.println(scanner.nextLine());
//If the client wants to exit, type quit and close the socket
if(msg.equalsIgnoreCase("quit")){
socket.close();
}
//Checks to see if client or server closed socket, if so, end the program
if (socket.isClosed()) {
System.out.println("Connection closed. Exiting...");
break;
}
else{
out.println(msg);
}
} }
readerThread.join();
} }
private static class Reader implements Runnable { private static class Reader implements Runnable {
private BufferedReader in; private BufferedReader in;
private Socket socket;
public Reader(Socket socket) throws IOException { public Reader(Socket socket) throws IOException {
this.socket = socket;
in = new BufferedReader(new InputStreamReader(socket.getInputStream())); in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} }
...@@ -63,15 +45,9 @@ public class BavlsikClient { ...@@ -63,15 +45,9 @@ public class BavlsikClient {
System.out.println(message); System.out.println(message);
} }
} catch (IOException e) { } catch (IOException e) {
System.out.println("Disconnected from server."); System.out.println("Error reading from server: " + e);
} finally {
try {
socket.close();
} catch (IOException e) {
System.out.println("Error closing socket: " + e);
}
} }
} }
} }
} }
...@@ -9,18 +9,14 @@ import java.io.PrintWriter; ...@@ -9,18 +9,14 @@ import java.io.PrintWriter;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.ServerSocket; import java.net.ServerSocket;
import java.net.Socket; import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
/** /**
* This class establishes a passcode protected chat server. Each client that connects *
* is handled by a new thread and messages are broadcast to all connected clients.
* @author tbavlsik * @author tbavlsik
*/ */
public class BavlsikServer { public class BavlsikServer {
// the set clientWriters contains form all sockets the active PrintStream // the set clientWriters contains form all sockets the active PrintStream
private static Set<PrintWriter> clientWriters = new HashSet<>(); private static Set<PrintWriter> clientWriters = new HashSet<>();
...@@ -28,40 +24,25 @@ public class BavlsikServer { ...@@ -28,40 +24,25 @@ public class BavlsikServer {
* @param args the command line arguments * @param args the command line arguments
*/ */
public static void main(String[] args) { public static void main(String[] args) {
ArrayList passcodes = new ArrayList<>(Arrays.asList(1, 29, 97));//Very secret passcode, wonder where those numbers came from...
System.out.println(BavlsikServer.class.getName() + " has started..."); // it helps debugging to put this on console first System.out.println(BavlsikServer.class.getName() + " has started..."); // it helps debugging to put this on console first
try (ServerSocket listener = new ServerSocket(2317)) { try (ServerSocket listener = new ServerSocket(2317)) {
while (true) { while (true) {
Handler handler = new Handler(listener.accept()); // create a new thread writing and reading to and from the new socket Handler handler = new Handler(listener.accept()); // create a new thread writing and reading to and from the new socket
OutputStream os = handler.socket.getOutputStream(); OutputStream os = handler.socket.getOutputStream();
PrintStream ps = new PrintStream(os); PrintStream ps = new PrintStream(os);
InetAddress remoteAddress = handler.socket.getInetAddress(); InetAddress remoteAddress = handler.socket.getInetAddress();
int remotePort = handler.socket.getPort(); int remotePort = handler.socket.getPort();
String message = remoteAddress.getHostName() + "=" + remoteAddress.getHostAddress() + ", " + remotePort + " has connected to the server."; String message = remoteAddress.getHostName() + "=" + remoteAddress.getHostAddress() + ", " + remotePort + " has connected to the server.";
System.out.println(message); System.out.println(message);
BufferedReader reader = new BufferedReader(new InputStreamReader(handler.socket.getInputStream())); ps.println("Welcome " + remoteAddress.getHostName() + "=" + remoteAddress.getHostAddress() + ", " + remotePort + " to the group chat!");
ps.println("Enter a passcode:"); for (PrintWriter writer : clientWriters) {
String passInput = reader.readLine(); // read the entire line as a string
int pass = Integer.parseInt(passInput.trim());
//Validate the client entered passcode
if (passcodes.contains(pass)) {
ps.println("Welcome " + remoteAddress.getHostName() + "=" + remoteAddress.getHostAddress() + ", " + remotePort + " to the group chat!");
for (PrintWriter writer : clientWriters) {
writer.println(message); writer.println(message);
} }
ps.flush(); ps.flush();
handler.start(); handler.start();
} else {//Kick the client from the server.
ps.println("Not a valid passcode.");
System.out.println(remoteAddress.getHostName() + "=" + remoteAddress.getHostAddress() + ", " + remotePort + " entered an incorrect passcode; disconnecting.");
handler.socket.close();
}
} }
} catch (IOException e) { }catch (IOException e) {
System.err.println("Problem with " + BavlsikServer.class.getName() + " networking: " + e); System.err.println("Problem with " + BavlsikServer.class.getName() + " networking: " + e);
// Provide more helpful information to user if exception occurs due to running twice at one time // Provide more helpful information to user if exception occurs due to running twice at one time
...@@ -69,11 +50,10 @@ public class BavlsikServer { ...@@ -69,11 +50,10 @@ public class BavlsikServer {
System.err.println("*** Be sure to stop any other running instances of programs using this port!"); System.err.println("*** Be sure to stop any other running instances of programs using this port!");
} }
} }
} }
private static class Handler extends Thread { private static class Handler extends Thread {
public final Socket socket; public final Socket socket;
private PrintWriter out; private PrintWriter out;
private BufferedReader in; private BufferedReader in;
...@@ -91,10 +71,10 @@ public class BavlsikServer { ...@@ -91,10 +71,10 @@ public class BavlsikServer {
synchronized (clientWriters) { synchronized (clientWriters) {
clientWriters.add(out); clientWriters.add(out);
} }
//Read in the message sent by the client and then send it to all other connected clients
String message; String message;
while ((message = in.readLine()) != null) { while ((message = in.readLine()) != null) {
String outputMessage = socket.getInetAddress().getHostName() + "=" + socket.getInetAddress().getHostAddress() + ", " + socket.getPort() + ": " + message; String outputMessage = socket.getInetAddress().getHostName() + "=" + socket.getInetAddress().getHostAddress() + ", " + socket.getPort()+ ": " + message;
System.out.println(outputMessage); System.out.println(outputMessage);
for (PrintWriter writer : clientWriters) { for (PrintWriter writer : clientWriters) {
writer.println(outputMessage); writer.println(outputMessage);
...@@ -103,9 +83,6 @@ public class BavlsikServer { ...@@ -103,9 +83,6 @@ public class BavlsikServer {
} catch (IOException e) { } catch (IOException e) {
System.out.println("Error handling client: " + e); System.out.println("Error handling client: " + e);
} finally { } finally {
//if a client disconnects or is kicked from the server, close the socket and broadcast the message to the chat
String disconnectMessage = (socket.getInetAddress().getHostName() + "=" + socket.getInetAddress().getHostAddress() + ", " + socket.getPort() + " has disconnected.");
System.out.println(disconnectMessage);
try { try {
socket.close(); socket.close();
} catch (IOException e) { } catch (IOException e) {
...@@ -115,11 +92,8 @@ public class BavlsikServer { ...@@ -115,11 +92,8 @@ public class BavlsikServer {
synchronized (clientWriters) { synchronized (clientWriters) {
clientWriters.remove(out); clientWriters.remove(out);
} }
for (PrintWriter writer : clientWriters) {
writer.println(disconnectMessage);
}
} }
} }
} }
} }
...@@ -3,18 +3,8 @@ ...@@ -3,18 +3,8 @@
*** ***
## Description ## Description
Modification of TcpExample3 and adding some code to implement a passcode protected Modification of TcpExample3 and adding some code to implement a chat room with multiple clients.
chat room with multiple clients.
The 'BavlsikServer' class sets up a server that listens for incoming client connections The 'BavlsikServer' class sets up a server that listens for incoming client connections on port 2317. When a client connects, the server creates a new handler thread for managing communication with that client. Each client's messages are broadcast to all other connected clients.
on port 2317. When a client connects, the server creates a new handler thread for
managing communication with that client. After the connection is established,
the server prompts the client for a passcode. If the client enters a valid passcode
they are added to teh chat room where each client's messages are broadcast to all
other connected clients. If the passcode is entered incorrectly, they client is
disconnected from the server. If a client enters 'quit' they disconnect from the server.
The 'BavlsikClient' class connects to a server running on localhost at port 2317. The 'BavlsikClient' class connects to a server running on localhost at port 2317. It sends user input from the console to the server and displays messages received from the server.
If the client enters a correct passcode, they are added to the chatroom, if it is \ No newline at end of file
incorrect they are disconnecte. The client then 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.Lennon;
//import TcpExamples.TcpExample4Client;
//import TcpExamples.TcpExample4DispatchServer;
import java.io.*;
import java.net.*;
import java.util.Random;
/**
* <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 LennonHW2HandlerThread 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
*/
LennonHW2HandlerThread(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 ("*** LennonHW2HandlerThread is not a standalone executable progam.");
System.out.println ("*** Please run LennonHW2DispatchServer 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(LennonHW2HandlerThread.class.getName() + " starting to handle a thread...");
// get the connection output stream, then wait a period of time.
Random random = new Random();
int randNum = random.nextInt(10)+1;
OutputStream os = socket.getOutputStream();
PrintStream ps = new PrintStream(os);
ps.println("I'm thinking of a number between 1 and 10. Can you guess it?" );
ps.flush(); // make sure that it indeed escapes current process and reaches the client
InputStream is = socket.getInputStream();
Reader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String userGuess = br.readLine(); // blocks
String serverResponse = null;
try{
int userNum = Integer.parseInt(userGuess);
if (userNum == randNum){
serverResponse = "Good job. You got it.";
}else{
serverResponse = "You're wrong. It was " + randNum;
}
}catch(NumberFormatException e){
System.out.println("Something went wrong. Guess was not a number" + e);
serverResponse = "Something went wrong. Anyway, my number was " + randNum;
}
final long TIMEOUT = 500; // 2000 milliseconds = 2 seconds, 500 milliseconds = 0.5 seconds
System.out.println(LennonHW2HandlerThread.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(serverResponse );
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(LennonHW2HandlerThread.class.getName() + " finished handling a thread, now exit.");
}
catch(IOException | InterruptedException e) // either a networking or a threading problem
{
System.out.println("Problem with " + LennonHW2HandlerThread.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!");
}
}
}
## Homework 2: TCP Client/Server Networking ## Homework 2: UDP Multicast Client/Server Networking
Deliverables: Deliverables:
...@@ -21,8 +21,4 @@ Approach: ...@@ -21,8 +21,4 @@ Approach:
4. Create a simple illustration of the communications exchange in a [UML Sequence Diagram](https://en.wikipedia.org/wiki/Sequence_diagram). 4. Create a simple illustration of the communications exchange in a [UML Sequence Diagram](https://en.wikipedia.org/wiki/Sequence_diagram).
Please see the [README.md](../../../README.md) in the parent Please see the [README.md](../../../README.md) in the parent
[assignments](../../../../assignments) directory for detailed instructions. [assignments](../../../../assignments) directory for detailed instructions.
\ No newline at end of file
Of special note, produce good Javadoc results through proper documentation of
source code and includion of a package-info.java summary. NetBeans makes it
pretty easy to do so.
\ No newline at end of file
# Rene Romero Homework 2
***
## Description
Modification to TCPExample4 to show the Message of the day (MOTD), depending on the day of the week.
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.
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/
package MV3500Cohort2024JulySeptember.homework2.Romero;
import java.io.*;
import java.net.*;
import java.time.LocalDate;
import java.time.DayOfWeek;
//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 RomeroClientHW2
{
/** Default constructor */
public RomeroClientHW2()
{
// default constructor
}
/**
* Program invocation, execution starts here
* @param args command-line arguments
*/
public static void main(String[] args) {
DataInputStream in;
DataOutputStream out;
LocalDate currentDate = LocalDate.now();
DayOfWeek day = currentDate.getDayOfWeek();
System.out.println("Current date: " + currentDate);
System.out.println("Today is: " + day + "\n");
System.out.println(RomeroClientHW2.class.getName() + " creating new socket ...");
try {
Socket clientConnectionSocket = new Socket("localhost", 2317);
in = new DataInputStream(clientConnectionSocket.getInputStream());
out = new DataOutputStream(clientConnectionSocket.getOutputStream());
out.writeUTF(day.name());
String mensaje = in.readUTF();
System.out.println(mensaje);
clientConnectionSocket.close();
} catch (IOException e) {
System.out.println("Problem with " + RomeroClientHW2.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!");
}
}
}
}
package MV3500Cohort2024JulySeptember.homework2.Romero;
import java.io.DataInputStream;
import java.io.DataOutputStream;
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)
{
DataInputStream in;
DataOutputStream out;
try {
ServerSocket serverSocket = new ServerSocket(2317);
System.out.println("Server has been initializated ... ");
System.out.println("Witing for conections ...");
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 + "...");
// 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
}
}
...@@ -5,6 +5,6 @@ ...@@ -5,6 +5,6 @@
## Description ## Description
Modification of TcpExample3 and adding some code to implement a chat room with multiple clients. Modification of TcpExample3 and adding some code to implement a chat room with multiple clients.
The 'SchnitzlerServer' class sets up a server that listens for incoming client connections on port 2317. When a client connects, the server creates a new handler thread for managing communication with that client. For a successful connection a password must be entered. After that each client's messages are broadcast to all other connected clients. The 'SchnitzlerServer' class sets up a server that listens for incoming client connections on port 2317. When a client connects, the server creates a new handler thread for managing communication with that client. Each client's messages are broadcast to all other connected clients.
The 'SchnitzlerClient' class connects to a server running on localhost at port 2317. It sends user input from the console to the server and displays messages received from the server. The 'SchnitzlerClient' class connects to a server running on localhost at port 2317. It sends user input from the console to the server and displays messages received from the server.
\ No newline at end of file
...@@ -8,8 +8,7 @@ import java.net.Socket; ...@@ -8,8 +8,7 @@ import java.net.Socket;
import java.util.Scanner; import java.util.Scanner;
/** /**
* Homework2: Client which connect to a server and prints all incoming messages of the server to the console. *
*
* @author simonschnitzler * @author simonschnitzler
*/ */
public class SchnitzlerClient { public class SchnitzlerClient {
...@@ -22,28 +21,25 @@ public class SchnitzlerClient { ...@@ -22,28 +21,25 @@ public class SchnitzlerClient {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
Socket socket = new Socket(LOCALHOST, 2317); Socket socket = new Socket(LOCALHOST, 2317);
Thread connection = new Thread(new Reader(socket)); new Thread(new Reader(socket)).start();
connection.start();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Scanner scanner = new Scanner(System.in); Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine() && connection.isAlive()) { while (scanner.hasNextLine()) {
out.println(scanner.nextLine()); out.println(scanner.nextLine());
} }
} }
private static class Reader implements Runnable { private static class Reader implements Runnable {
private BufferedReader in; private BufferedReader in;
private final Socket socket;
public Reader(Socket socket) throws IOException { public Reader(Socket socket) throws IOException {
this.socket = socket; in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
} }
@Override @Override
public void run() { public void run() {
try (socket){ try {
String message; String message;
while ((message = in.readLine()) != null) { while ((message = in.readLine()) != null) {
System.out.println(message); System.out.println(message);
......
...@@ -3,6 +3,8 @@ package MV3500Cohort2024JulySeptember.homework2.Schnitzler; ...@@ -3,6 +3,8 @@ package MV3500Cohort2024JulySeptember.homework2.Schnitzler;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.ServerSocket; import java.net.ServerSocket;
...@@ -11,8 +13,7 @@ import java.util.HashSet; ...@@ -11,8 +13,7 @@ import java.util.HashSet;
import java.util.Set; import java.util.Set;
/** /**
* Homework2: Chatserver, which is waiting for clients to connect. The clients need to enter a password for a successfull connection. After a successfull connection all messages will be sent to all clients. *
*
* @author simonschnitzler * @author simonschnitzler
*/ */
public class SchnitzlerServer { public class SchnitzlerServer {
...@@ -26,15 +27,20 @@ public class SchnitzlerServer { ...@@ -26,15 +27,20 @@ public class SchnitzlerServer {
System.out.println(SchnitzlerServer.class.getName() + " has started..."); // it helps debugging to put this on console first System.out.println(SchnitzlerServer.class.getName() + " has started..."); // it helps debugging to put this on console first
try (ServerSocket listener = new ServerSocket(2317)) { try (ServerSocket listener = new ServerSocket(2317)) {
while (true) { while (true) {
Socket socket = listener.accept(); Handler handler = new Handler(listener.accept()); // create a new thread writing and reading to and from the new socket
int remotePort = socket.getPort(); OutputStream os = handler.socket.getOutputStream();
InetAddress remoteAddress = socket.getInetAddress(); PrintStream ps = new PrintStream(os);
String message = remoteAddress.getHostName() + "=" + remoteAddress.getHostAddress() + ", " + remotePort + " tries to connect to the server.";
System.out.println(message);
Handler handler = new Handler(socket);
handler.start();
InetAddress remoteAddress = handler.socket.getInetAddress();
int remotePort = handler.socket.getPort();
String message = remoteAddress.getHostName() + "=" + remoteAddress.getHostAddress() + ", " + remotePort + " has connected to the server.";
System.out.println(message);
ps.println("Welcome " + remoteAddress.getHostName() + "=" + remoteAddress.getHostAddress() + ", " + remotePort + " to the group chat!");
for (PrintWriter writer : clientWriters) {
writer.println(message);
}
ps.flush();
handler.start();
} }
}catch (IOException e) { }catch (IOException e) {
System.err.println("Problem with " + SchnitzlerServer.class.getName() + " networking: " + e); System.err.println("Problem with " + SchnitzlerServer.class.getName() + " networking: " + e);
...@@ -61,49 +67,19 @@ public class SchnitzlerServer { ...@@ -61,49 +67,19 @@ public class SchnitzlerServer {
try { try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream())); in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true); out = new PrintWriter(socket.getOutputStream(), true);
InetAddress remoteAddress = socket.getInetAddress(); synchronized (clientWriters) {
int remotePort = socket.getPort();
out.println("Speak, friend, and enter!");
String answer = in.readLine();
if("Mellon".equals(answer)){
String message = remoteAddress.getHostName() + "=" + remoteAddress.getHostAddress() + ", " + remotePort + " has connected to the server.";
System.out.println(message);
out.println("Welcome " + remoteAddress.getHostName() + "=" + remoteAddress.getHostAddress() + ", " + remotePort + " to the group chat!");
for (PrintWriter writer : clientWriters) {
writer.println(message);
}
out.flush();
synchronized (clientWriters) {
clientWriters.add(out); clientWriters.add(out);
} }
while ((message = in.readLine()) != null) { String message;
String outputMessage = socket.getInetAddress().getHostName() + "=" + socket.getInetAddress().getHostAddress() + ", " + socket.getPort()+ ": " + message; while ((message = in.readLine()) != null) {
System.out.println(outputMessage); String outputMessage = socket.getInetAddress().getHostName() + "=" + socket.getInetAddress().getHostAddress() + ", " + socket.getPort()+ ": " + message;
for (PrintWriter writer : clientWriters) {
writer.println(outputMessage);
}
}
String outputMessage = socket.getInetAddress().getHostName() + "=" + socket.getInetAddress().getHostAddress() + ", " + socket.getPort()+ " has disconnected!";
System.out.println(outputMessage); System.out.println(outputMessage);
for (PrintWriter writer : clientWriters) { for (PrintWriter writer : clientWriters) {
writer.println(outputMessage); writer.println(outputMessage);
} }
} }
else{
try (socket) {
String message = remoteAddress.getHostName() + "=" + remoteAddress.getHostAddress() + ", " + remotePort + ": Connection denied!";
System.out.println(message);
out.println(message);
socket.close();
}catch (IOException e) {
System.out.println("Couldn't close a socket, what's going on?");
}
}
} catch (IOException e) { } catch (IOException e) {
System.out.println("Error handling client: " + e); System.out.println("Error handling client: " + e);
} finally { } finally {
......
/**
* 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.Smith;
package MV3500Cohort2024JulySeptember.homework2.Timberlake; package MV3500Cohort2024JulySeptember.homework2.Timberlake;
import java.io.BufferedReader; import java.net.DatagramPacket;
import java.io.InputStreamReader; import java.net.DatagramSocket;
import java.io.OutputStream; import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner; import java.util.Scanner;
import java.io.PrintWriter;
/** /**
* *
* @author Jack * @author Jack
*/ */
public class Client_HW2 { public class Client_HW2 {
public static void main(String[] args) { public static void main(String[] args) {
Socket socket = null; DatagramSocket socket = null;
Scanner scanner = new Scanner(System.in); Scanner scanner = new Scanner(System.in);
try { try {
// Create a socket to communicate with the server // Create a socket to communicate with the server
socket = new Socket("192.168.56.1", 9876); // change IP depending on server machine socket = new DatagramSocket();
InetAddress serverAddress = InetAddress.getByName("localhost"); // Server address (localhost for testing)
PrintWriter outputWriter = new PrintWriter(socket.getOutputStream(), true); byte[] sendData = new byte[1024]; // Buffer to store data to send
BufferedReader inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); byte[] receiveData = new byte[1024]; // Buffer to store received data
// Receive and display server messages
System.out.println(inputReader.readLine()); // Enter name
String name = scanner.nextLine();
outputWriter.println(name); // Send name
outputWriter.flush();
System.out.println(inputReader.readLine()); // Enter fav color System.out.print("Let's play a game!!\n");
String color = scanner.nextLine(); System.out.print("Try guessing a number between 1-100\n");
outputWriter.println(color); // Send fav color
outputWriter.flush();
// Receive and display initial messages from the server
// Empty string means init messages over
String serverMessage;
while (!(serverMessage = inputReader.readLine()).isEmpty()) {
System.out.println(serverMessage);
}
while(true) { while(true) {
System.out.print("Enter your guess: "); System.out.print("Enter your guess: ");
String guess = scanner.nextLine(); //Read user input String guess = scanner.nextLine(); //Read user input
outputWriter.println(guess); //Send guess to server sendData = guess.getBytes(); // Convert message to bytes
outputWriter.flush();
// Send guess to the server
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, 9876);
socket.send(sendPacket); // Send packet to server
// Receive response from server // Receive response from server
String response = inputReader.readLine(); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
System.out.println("Server Said: " + response); // print server response socket.receive(receivePacket); // Blocking call until a packet is received
String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Server Said: " + response); // Print received response
// End game
if (response.startsWith ("Good")) { if (response.startsWith ("Good")) {
break; //End the game break; //End the game
} }
...@@ -65,11 +49,7 @@ public class Client_HW2 { ...@@ -65,11 +49,7 @@ public class Client_HW2 {
scanner.close(); // Close scanner scanner.close(); // Close scanner
} }
if (socket != null && !socket.isClosed()) { if (socket != null && !socket.isClosed()) {
try { socket.close(); // Close the socket to release resources
socket.close(); // Close the socket to release resources
} catch (Exception e) {
e.printStackTrace();
}
} }
} }
} }
......
package MV3500Cohort2024JulySeptember.homework2.Timberlake;
/**
*
* @author Jack
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Random;
import java.util.HashMap;
import java.util.Map;
public class GameHandler implements Runnable {
private Socket clientSocket;
private int numToGuess;
private static final Map<String, String> userCredentials = new HashMap<>();
static {
// User credentials dictionary
userCredentials.put("Jack", "blue");
userCredentials.put("Stephen", "green");
userCredentials.put("Don", "red");
}
public GameHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
Random random = new Random();
this.numToGuess = random.nextInt(100) + 1; // Initialize random number 1-100
}
@Override
public void run() {
try (BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter outputWriter = new PrintWriter(clientSocket.getOutputStream(), true)) {
// Request name from client
outputWriter.println("Enter your name:");
outputWriter.flush();
String name = inputReader.readLine();
// Request favorite color from client
outputWriter.println("Enter your favorite color:");
outputWriter.flush();
String color = inputReader.readLine();
// Check credentials and start game
// Kill connection if credentials are wrong
if (!(userCredentials.containsKey(name) && userCredentials.get(name).equalsIgnoreCase(color))) {
outputWriter.println("INTRUDER! INTRUDER! TERMINATING CONNECTION.");
clientSocket.close();
} else {
outputWriter.println("Authentication successful! Welcome, " + name + ".");
outputWriter.println("Let's play a game!!");
outputWriter.println("Try guessing a number between 1-100");
outputWriter.println(""); // Send an empty line to signal the end of initial messages
}
int count = 1;
boolean isRunning = true;
while (isRunning) {
// Read message from client
String message = inputReader.readLine();
System.out.println("Client sent: " + message); // Print received message
String response;
try {
int guess = Integer.parseInt(message.trim());
if (guess < numToGuess) {
response = "Guess Higher";
count++;
} else if (guess > numToGuess) {
response = "Guess Lower";
count++;
} else {
response = "Good Job " + name + "!! That took you " + count + " tries!";
isRunning = false;
}
} catch (NumberFormatException e) {
response = "Invalid input. Enter a number.";
}
// Send response to client
outputWriter.println(response);
}
} catch (Exception e) {
e.printStackTrace(); // Print any exceptions that occur
} finally {
try {
if (clientSocket != null && !clientSocket.isClosed()) {
clientSocket.close(); // Close the client socket to release resources
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package MV3500Cohort2024JulySeptember.homework2.Timberlake; package MV3500Cohort2024JulySeptember.homework2.Timberlake;
import java.net.ServerSocket; import java.net.DatagramPacket;
import java.net.Socket; import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Random;
/** /**
* *
* @author Jack * @author Jack
*/ */
public class Server_HW2 { public class Server_HW2 {
public static void main(String[] args) { public static void main(String[] args) {
ServerSocket serverSocket = null; DatagramSocket socket = null;
Random random = new Random();
int numToGuess = random.nextInt(100) + 1;
//System.out.println("Magic Number Is: " + numToGuess);
try { try {
// Create a socket to listen on port 9876 // Create a socket to listen on port 9876
serverSocket = new ServerSocket(9876); socket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024]; // Buffer to store incoming data
byte[] sendData = new byte[1024]; // Buffer to store outgoing data
int count = 1;
System.out.println("Server has started, waiting for client..."); System.out.println("Server has started, waiting for client...");
while (true) {
// Accept client connection
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected");
// Create GameHandler to handle client boolean isRunning = true;
GameHandler gameHandler = new GameHandler(clientSocket); while (isRunning) {
// Receive packet from client
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket); // Blocking call until a packet is received
String message = new String(receivePacket.getData(), 0, receivePacket.getLength()); //Receive packet
InetAddress clientAddress = receivePacket.getAddress(); //Save IP for response
int clientPort = receivePacket.getPort(); //Save port for response
System.out.println("Client sent: " + message); // Print received message
// Create new thread to handle the game String response;
Thread thread = new Thread(gameHandler); try {
thread.start(); int guess = Integer.parseInt(message.trim());
if (guess < numToGuess) {
response = "Guess Higher";
count++;
} else if (guess > numToGuess) {
response = "Guess Lower";
count++;
} else {
response = "Good Job!! That took you " + count + " tries!";
isRunning = false;
}
} catch (NumberFormatException e) {
response = "Invalid input. Enter a number.";
}
// Prepare response to client
sendData = response.getBytes(); // Convert response message to bytes
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
socket.send(sendPacket); // Send response packet to client
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); // Print any exceptions that occur e.printStackTrace(); // Print any exceptions that occur
} finally { } finally {
try { if (socket != null && !socket.isClosed()) {
if (serverSocket != null && !serverSocket.isClosed()) { socket.close(); // Close the socket to release resources
serverSocket.close(); // Close the server socket to release resources
}
} catch (Exception e) {
e.printStackTrace();
} }
} }
} }
......
## Homework 2:
For this assignment, I utilized the framework classes from the example 4 we disected in class.
The three files—HW2Client, HW2Server, HW2Thread— work together to create a simple client-server application.
The server class is the main server program, listening for incoming client connections on a specified
port 2317. When the client connects, the server runs HW2Thread to handle the communication with that client,
allowing the server to manage multiple clients concurrently. The thread class is responsible for processing the client's
input and sending an appropriate response back, after which it closes the connection. On the client side,
the client class connects to the server, sends a message "Ethan", and receives a response. The client measures
the time taken for the interaction and handles multiple iterations if specified. Overall, the server/client interact
through a series of messages, with the server capable of handling multiple clients simultaneously through threading.
\ No newline at end of file
package MV3500Cohort2024JulySeptember.homework2.Yu;
import java.io.*;
import java.net.*;
//import java.time.LocalTime; // conversion?
/**
* @author Jin Hong Yu
*/
public class YuHW2Client {
/**
* Default constructor
*/
public YuHW2Client() {
// 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(YuHW2Client.class.getName() + " start, loop " + MAX_LOOP_COUNT + " times");
System.out.println("=======================================================");
for (int loopCount = 1; loopCount <= MAX_LOOP_COUNT; loopCount++) {
System.out.println(YuHW2Client.class.getName() + " creating new socket #" + loopCount + "...");
long startTime = System.currentTimeMillis();
Socket socket = new Socket(DESTINATION_HOST, 2317);
PrintStream ps = new PrintStream(socket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// Knock Knock joke sequence
ps.println("Knock Knock");
ps.flush();
System.out.println("Client: Knock Knock");
String serverResponse = br.readLine(); // blocks
System.out.println("Server: " + serverResponse);
if ("Who's there?".equals(serverResponse)) {
ps.println("Hatch");
ps.flush();
System.out.println("Client: Hatch");
}
serverResponse = br.readLine();
System.out.println("Server: " + serverResponse);
if ("Hatch who?".equals(serverResponse)) {
ps.println("God Bless You!");
ps.flush();
System.out.println("Client: God Bless You!");
}
long readTime = System.currentTimeMillis();
long timeLength = readTime - startTime;
System.out.println(YuHW2Client.class.getName() + ": time msec required for sequence=" + timeLength);
System.out.println("=======================================================");
socket.close();
}
System.out.println(YuHW2Client.class.getName() + " complete");
} catch (IOException e) {
System.out.println("Problem with " + YuHW2Client.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.Yu;
import java.io.*;
import java.net.*;
/**
* @author Jin Hong Yu
*/
public class YuHW2HandlerThread 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
*/
YuHW2HandlerThread(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 ("*** YuHW2HandlerThread 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(YuHW2HandlerThread.class.getName() + " starting to handle a thread...");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
// Sequence of the Knock Knock joke
String clientMessage = in.readLine();
System.out.println("Client: " + clientMessage);
if ("Knock Knock".equals(clientMessage)) {
ps.println("Who's there?");
ps.flush();
}
clientMessage = in.readLine();
System.out.println("Client: " + clientMessage);
if ("Hatch".equals(clientMessage)) {
ps.println("Hatch who?");
ps.flush();
}
clientMessage = in.readLine();
System.out.println("Client: " + clientMessage);
if ("God Bless You!".equals(clientMessage)) {
System.out.println("Joke sequence complete.");
}
socket.close(); // all clear, no longer need socket
System.out.println(YuHW2HandlerThread.class.getName() + " finished handling a thread, now exit.");
} catch(IOException e) {
System.out.println("Problem with " + YuHW2HandlerThread.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!");
}
}
}
}
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