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

Merge origin/master

parents 900e79c7 53dfef95
No related branches found
No related tags found
No related merge requests found
package MV3500Cohort2024JulySeptember.homework2.Williams; package MV3500Cohort2024JulySeptember.homework2.Williams;
import java.net.DatagramPacket; import java.io.BufferedReader;
import java.net.DatagramSocket; import java.io.IOException;
import java.net.InetAddress; import java.io.InputStream;
import java.util.Scanner; import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
/** /**
* Client file for HW2. * Client file for HW2.
...@@ -13,45 +16,84 @@ import java.util.Scanner; ...@@ -13,45 +16,84 @@ import java.util.Scanner;
public class HW2Client { public class HW2Client {
/** /**
* @param args the command line arguments * Default constructor
*/
public HW2Client() {
}
static String DESTINATION_HOST = "localhost";
static int DESTINATION_PORT = 2317;
static int MAX_LOOP_COUNT = 1;
/**
* @param args command-line arguments
*/ */
public static void main(String[] args) { public static void main(String[] args) {
DatagramSocket socket = null; if (args.length > 0) {
Scanner scanner = new Scanner(System.in); DESTINATION_HOST = args[0];
try { }
socket = new DatagramSocket(); if (args.length > 1) {
InetAddress serverAddress = InetAddress.getByName("localhost"); DESTINATION_PORT = Integer.parseInt(args[1]);
byte[] sendData = new byte[1024]; }
byte[] receiveData = new byte[1024]; if (args.length > 2) {
MAX_LOOP_COUNT = Integer.parseInt(args[2]);
System.out.print("Can you solve my riddle??\n"); }
System.out.print("Try to solve the riddle: I speak without a mouth and hear without ears. I have no body, but I come alive with wind. What am I?\n");
while (true) { System.out.println("=======================================================");
System.out.print("Enter your answer: ");
String answer = scanner.nextLine(); for (int loopCount = 1; loopCount <= MAX_LOOP_COUNT; loopCount++) {
sendData = answer.getBytes(); System.out.println(HW2Client.class.getName() + " creating new socket:");
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, 9876); long startTime = System.currentTimeMillis();
socket.send(sendPacket); Socket socket = null;
BufferedReader br = null;
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); PrintWriter pw = null;
socket.receive(receivePacket);
String response = new String(receivePacket.getData(), 0, receivePacket.getLength()); try {
System.out.println("Server Said: " + response); socket = new Socket(DESTINATION_HOST, DESTINATION_PORT);
InputStream is = socket.getInputStream();
if (response.startsWith("Good")) { br = new BufferedReader(new InputStreamReader(is));
break; OutputStream os = socket.getOutputStream();
pw = new PrintWriter(os, true);
String serverMessage = br.readLine();
System.out.println("Server: " + serverMessage);
String clientResponse = "Ethan";
pw.println(clientResponse);
System.out.println("Client: " + clientResponse);
String serverFinalResponse = br.readLine();
long readTime = System.currentTimeMillis();
long timeLength = readTime - startTime;
System.out.println("Server response: " + serverFinalResponse);
System.out.println(HW2Client.class.getName() + ": time msec required for read = " + timeLength);
System.out.println("=======================================================");
} catch (IOException e) {
System.out.println("Problem with " + HW2Client.class.getName() + " networking:");
System.out.println("Error: " + e);
if (e instanceof java.net.BindException) {
System.out.println("*** Be sure to stop any other running instances of programs using this port!");
}
} finally {
try {
if (br != null) {
br.close();
}
if (pw != null) {
pw.close();
}
if (socket != null && !socket.isClosed()) {
socket.close();
}
} catch (IOException e) {
System.out.println("Error closing resources: " + e);
} }
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
if (socket != null && !socket.isClosed()) {
socket.close();
} }
} }
System.out.println(HW2Client.class.getName() + " complete");
} }
} }
package MV3500Cohort2024JulySeptember.homework2.Williams; package MV3500Cohort2024JulySeptember.homework2.Williams;
import java.net.DatagramPacket; import java.io.IOException;
import java.net.DatagramSocket; import java.io.PrintWriter;
import java.net.InetAddress; import java.net.ServerSocket;
import java.net.Socket;
/** /**
* Server file for HW2. * Server file for HW2.
...@@ -12,50 +13,49 @@ import java.net.InetAddress; ...@@ -12,50 +13,49 @@ import java.net.InetAddress;
public class HW2Server { public class HW2Server {
/** /**
* @param args the command line arguments * Default constructor
*/ */
public static void main(String[] args) { public HW2Server() {
DatagramSocket socket = null;
String riddleAnswer = "echo"; }
/**
* @param args command-line arguments
*/
public static void main(String[] args) {
try { try {
socket = new DatagramSocket(9876); ServerSocket serverSocket = new ServerSocket(2317);
byte[] receiveData = new byte[1024]; HW2Thread handlerThread;
byte[] sendData = new byte[1024]; Socket clientConnection;
int count = 1;
System.out.println("Server has started, waiting for client..."); int connectionCount = 0;
boolean isRunning = true; System.out.println(HW2Server.class.getName() + " ready to accept socket connections...");
while (isRunning) { while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientConnection = serverSocket.accept();
socket.receive(receivePacket);
String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
System.out.println("Client sent: " + message);
String response;
if (message.trim().equalsIgnoreCase(riddleAnswer)) {
response = "Good Job!! You solved the riddle in " + count + " tries!";
isRunning = false;
} else {
response = "Wrong answer. Try again!";
count++;
}
sendData = response.getBytes(); connectionCount++;
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
socket.send(sendPacket); try {
PrintWriter out = new PrintWriter(clientConnection.getOutputStream(), true);
out.println("I'd like to shake your hand. What's your name?");
} catch (IOException e) {
System.out.println("Error sending initial message to client: " + e);
}
System.out.println("=============================================================");
System.out.println(HW2Server.class.getName() + ".handlerThread created for connection #" + connectionCount + "...");
handlerThread = new HW2Thread(clientConnection);
handlerThread.start();
System.out.println(HW2Server.class.getName() + ".handlerThread is now dispatched and running, using most recent connection...");
} }
} catch (Exception e) { } catch (IOException e) {
e.printStackTrace(); System.out.println("Problem with " + HW2Server.class.getName() + " networking:");
} finally { System.out.println("Error: " + e);
if (socket != null && !socket.isClosed()) { if (e instanceof java.net.BindException) {
socket.close(); System.out.println("*** Be sure to stop any other running instances of programs using this port!");
} }
} }
System.out.println("=============================================================");
} }
} }
package MV3500Cohort2024JulySeptember.homework2.Williams;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
/**
*
* @author ethanjwilliams
*/
public class HW2Thread extends Thread {
/**
* The socket connection to a client
*/
private final Socket socket;
private static int connectionCount = 0;
/**
* 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
*/
HW2Thread(Socket socket) {
this.socket = socket;
synchronized (HW2Thread.class) {
connectionCount++;
}
}
/**
* 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("*** HW2Thread is not a standalone executable progam.");
System.out.println("*** Please run HW2Server 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).
*/
@Override
public void run() {
BufferedReader br = null;
PrintStream ps = null;
try {
System.out.println(HW2Thread.class.getName() + " starting to handle a thread...");
InputStream is = socket.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
OutputStream os = socket.getOutputStream();
ps = new PrintStream(os);
String clientResponse = br.readLine();
System.out.println("Received from client: " + clientResponse);
if ("Ethan".equalsIgnoreCase(clientResponse.trim())) {
ps.println("Nice to meet you!");
} else {
ps.println("Say your name again.");
}
ps.flush();
System.out.println(HW2Thread.class.getName() + " finished handling a thread, now exit.");
} catch (IOException e) {
System.out.println("Problem with " + HW2Thread.class.getName() + " networking:");
System.out.println("Error: " + e);
if (e instanceof java.net.BindException) {
System.out.println("*** Be sure to stop any other running instances of programs using this port!");
}
} finally {
try {
if (br != null) {
br.close();
}
if (ps != null) {
ps.close();
}
socket.close();
} catch (IOException e) {
System.out.println("Error closing resources: " + e);
}
}
}
}
...@@ -33,27 +33,33 @@ public class TcpExample4DispatchServer ...@@ -33,27 +33,33 @@ public class TcpExample4DispatchServer
public static void main(String[] args) public static void main(String[] args)
{ {
try { try {
ServerSocket serverSocket = new ServerSocket(2317); ServerSocket serverSocket = new ServerSocket(2317);
Socket clientConnectionSocket;
TcpExample4HandlerThread handlerThread; TcpExample4HandlerThread handlerThread;
Socket clientConnection;
int connectionCount = 0; // state variable int connectionCount = 0; // state variable
System.out.println(TcpExample4DispatchServer.class.getName() + " ready to accept socket connections..."); System.out.println(TcpExample4DispatchServer.class.getName() + " ready to accept socket connections...");
while (true) // infinite loop while (true) // infinite loop
{ {
clientConnection = serverSocket.accept(); // block! until connected clientConnectionSocket = serverSocket.accept(); // block! until connected
connectionCount++; // unblocked, got another connection connectionCount++; // unblocked, got another connection
// TODO provide initial message *to the client* that we are handing off to a dispatch thread... because that is polite behavior. // TODO option for the student, provide initial message *to the client*
// plenty of code in Example3, we will let TcpExample4HandlerThread introduce itself // that we are handing off to a dispatch thread... because that is polite behavior.
// Plenty of code in Example3, we instead let our proxy thread
// TcpExample4HandlerThread introduce itself to the client.
System.out.println("============================================================="); System.out.println("=============================================================");
System.out.println(TcpExample4DispatchServer.class.getName() + ".handlerThread created for connection #" + connectionCount + "..."); System.out.println(TcpExample4DispatchServer.class.getName() + ".handlerThread created for connection #" + connectionCount + "...");
handlerThread = new TcpExample4HandlerThread(clientConnection); // hand off the aready-created, connected socket to constructor
// hand off this aready-created and connected socket to constructor
handlerThread = new TcpExample4HandlerThread(clientConnectionSocket);
handlerThread.start();// invokes the run() method in that object handlerThread.start();// invokes the run() method in that object
System.out.println(TcpExample4DispatchServer.class.getName() + ".handlerThread is now dispatched and running, using most recent connection..."); System.out.println(TcpExample4DispatchServer.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) { catch (IOException e) {
...@@ -64,6 +70,6 @@ public class TcpExample4DispatchServer ...@@ -64,6 +70,6 @@ public class TcpExample4DispatchServer
System.out.println("*** Be sure to stop any other running instances of programs using this port!"); System.out.println("*** Be sure to stop any other running instances of programs using this port!");
} }
} }
System.out.println("============================================================="); System.out.println("============================================================="); // execution complete
} }
} }
examples/src/TcpExamples/TcpExample4SequenceDiagram.png

17.6 KiB | W: | H:

examples/src/TcpExamples/TcpExample4SequenceDiagram.png

21.2 KiB | W: | H:

examples/src/TcpExamples/TcpExample4SequenceDiagram.png
examples/src/TcpExamples/TcpExample4SequenceDiagram.png
examples/src/TcpExamples/TcpExample4SequenceDiagram.png
examples/src/TcpExamples/TcpExample4SequenceDiagram.png
  • 2-up
  • Swipe
  • Onion skin
No preview for this file type
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