In java programming only. Assignment Tasks You are asked to develop a Server pro
ID: 3821877 • Letter: I
Question
In java programming only.
Assignment Tasks
You are asked to develop a Server program running on one computer, and a Client program running on another computer. (When you test your server and client programs on one computer, you may use Loopback IP Address 127.0.0.1, with which any packets sent out from this machine will immediately loop back to itself.) The Server will accept input from keyboard for system initialization, selection of menu items, human command and instructions, etc. It will also display information on the monitor, periodically send commands to the Client, and receive feedback from the Client. After receiving a command from the Server, the Client will send feedback to the Server, and displays some information of your interest.
Assignment tasks are described below:
(1) When the Server is started, it initializes the settings of the server’s IP addresses, port Server Keyboard Monitor Client TCP/IP Port No.: 3247 Monitor Keyboard 3 number, and the client’s IP address, etc., through command window arguments, e.g., header file, arguments to main(), keyboard input, or input from a configuration file which is a pure text file.
(2) Every 3 seconds, the Server sends the Client a command to ask for data, e.g., through a single letter “R” or “r” (request). (Timing control is required here. Using our examples in the lecture materials if you like.)
(3) After receiving the command from the Server, the Client sends back to the Server an ACK consisting of the client’s time (hh:mm:ss:???) and a random integer number between 0 and 100 with a uniform distribution. The Client may also display some useful information on its monitor. (Use a random generator to generate such random numbers. For example, rand()%101 and use srand(time(NULL)) to get a seed for rand(), where time() function is defined in header file time.h).
(4) The Server gets the feedback from the Client, and display the result.
(5) The Server reads keyboard input of various command and instructions. An obvious command is to terminate the Server program, e.g., using a single letter “E” or “e” (exit). When the Sever is to be terminated, the Server should also notify the Client of the Server’s termination so that the Client also terminates properly.
Monitor Monitor TCP/IP Server Client Port No.: 3247 Keyboard KeyboardExplanation / Answer
Find the below code with the step by step procedure
We will have two separate directories for this project
One is client and the other is server
Inside a client directory, we have two java classes named as client and clientThread
Find the below code for Client.java
*******************
import java.util.*;
import java.io.*;
import java.util.concurrent.atomic.AtomicLong;
/**
* This is the main Client class, which spawns ClientThreads which connect to the server. This class
* includes methods for obtaining the user's commands and validating them.
*/
public class Client {
private static String hostName;
// create a variable to initialize new threads with
private static Thread thrd = null;
// the threads are kept track of with a linked list
private static LinkedList<Thread> list = new LinkedList<Thread>();
// AtomicLong is a class that is synchronized, and can be used across
// multiple threads. Here it is used for benchmarking, to store the sum
// of the command completion times for all threads
private static AtomicLong totalTime = new AtomicLong(0);
// this AtomicLong is used to keep track of the current # of running threads
private static AtomicLong runningThreads = new AtomicLong(0);
private static boolean printOutput = true;
public static void main(String[] args) {
int menuSelection = 0;
int numProcesses = 1;
// if no hostname is provided, quit
if (args.length == 0) {
System.out.println("User did not enter a host name. Client program exiting.");
System.exit(1);
}
// until the user selects 8, the Exit option, keep looping and
// offering the menu again after running the queries to the server
else while (menuSelection != 8) {
// display the menu and get the user's choice
menuSelection = mainMenu();
// if 8, exit program
if (menuSelection == 8) {
System.out.println("Quitting.");
System.exit(0);
}
// if 7, ask which command should be run in the benchmark mode
// and how many connections to create
if (menuSelection == 7) {
printOutput = false;
menuSelection = benchmarkMenu();
numProcesses = numProcessesMenu();
}
// create threads. since numProcesses is initialized to 1 and gets reset
// at the end of this loop, if the user has not selected to benchmark
// a command, this loop will only create one process
totalTime.set(0);
runningThreads.set(numProcesses);
for (int i = 0; i < numProcesses; i++) {
// make a new thread, tell it the hostname to connect to
// and the command to run. It is also passed the totalTime object,
// so it can record how much time its command took to complete
thrd = new Thread(new ClientThread(args[0], menuSelection, totalTime, printOutput, runningThreads));
thrd.start(); // start the thread
list.add(thrd); // add the thread to the end of the linked list
}
// wait for all of the threads to complete before going to the top
// of the loop again. This ensures that all threads complete before the
// menu is shown again
for (int i = 0; i < numProcesses; i++) {
try {
// wait for the thread to finish
list.get(i).join();
} catch (InterruptedException e) {
// if the join interrupts the thread, print an error
e.printStackTrace();
}
}
// while runningThreads is not 0, there are still clients waiting for the server
// to send a response, so keep looping (waiting) until they are finished
while (runningThreads.get() != 0) {}
System.out.println("Average response time: " + (totalTime.get() / numProcesses) + " ms ");
numProcesses = 1;
printOutput = true;
}
}
//----------------------------------------------------------------------------
/**
* Function to prompt the user for a command to run
* @return command number 1-8
*/
public static int mainMenu() {
int menuSelection = 0;
// loop (and prompt again) until the user's input is an integer between 1 and 8
while ((menuSelection <= 0) || (menuSelection > 8)) {
System.out.println("The menu provides the following choices to the user: ");
System.out.println("1. Host current Date and Time 2. Host uptime "
+ "3. Host memory use 4. Host Netstat 5. Host current users "
+ " 6. Host running processes 7. Benchmark (measure mean response time) 8. Quit ");
System.out.print("Please provide number corresponding to the action you want to be performed: ");
Scanner sc = new Scanner(System.in);
if (sc.hasNextInt()) menuSelection = sc.nextInt();
}
return menuSelection;
}
/**
* Function to prompt the user for a benchmark command to run
* @return command number 1-6
*/
public static int benchmarkMenu() {
int menuSelection = 0;
// loop (and prompt again) until the user's input is an integer between 1 and 6
while ((menuSelection <= 0) || (menuSelection > 6)) {
System.out.println("Which command would you like to benchmark? ");
System.out.println("1. Host current Date and Time 2. Host uptime "
+ "3. Host memory use 4. Host Netstat 5. Host current users "
+ " 6. Host running processes");
System.out.print("Please provide number corresponding to the action you want to be performed: ");
Scanner sc = new Scanner(System.in);
if (sc.hasNextInt()) menuSelection = sc.nextInt();
}
return menuSelection;
}
/**
* Function to prompt the user for how many connections to make (for measuring the mean response time)
* @return number 1-100
*/
public static int numProcessesMenu() {
int menuSelection = 0;
// loop (and prompt again) until the user's input is an integer between 1 and 100
while ((menuSelection <= 0) || (menuSelection > 100)) {
System.out.print("How many connections to the server would you like to open? [1-100]: ");
Scanner sc = new Scanner(System.in);
if (sc.hasNextInt()) menuSelection = sc.nextInt();
}
return menuSelection;
}
}
*********************
ClientThread.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.net.ConnectException;
import java.util.concurrent.atomic.AtomicLong;
public class ClientThread extends Thread {
// every clientThread is passed which command to send to the server
int menuSelection;
// every clientThread is passed the hostname of the server to connect to
String hostName;
Socket socket = null;
// totalTime is used to keep the sum of response times for all threads. after all threads
// have completed it is divided by the total number of threads to get an
// average response time
AtomicLong totalTime;
// runningThreads is the total number of running threads. it is set to numThreads (the number
// of threads that are started) before any threads are started by the Client class. Every time
// a ClientThread finishes it will decrement runningThreads by one, so runningThreads == 0 when
// all threads have finished
AtomicLong runningThreads;
// each class is passed false for printOutput if the number of threads started is > 1. When running more
// than one client thread the clientThreads should not print output, input order to not clutter the screen
boolean printOutput;
// startTime and endTime are used to keep track of the current time when the thread conects to the
// server and when the thread gets a response from the server. The difference between the two
// (endTime - startTime) is the response time
long startTime;
long endTime;
ClientThread(String hostName, int menuSelection, AtomicLong totalTime, boolean printOutput, AtomicLong runningThreads) {
this.menuSelection = menuSelection;
this.hostName = hostName;
this.totalTime = totalTime;
this.printOutput = printOutput;
this.runningThreads = runningThreads;
}
public void run() {
PrintWriter out = null;
BufferedReader input = null;
try {
//creates a new Socket object and names it socket.
//Establishes the socket connection between the client & server
//name of the machine & the port number to which we want to connect
socket = new Socket(hostName, 3247);
if (printOutput) {
System.out.print("Establishing connection.");
}
//opens a PrintWriter on the socket input autoflush mode
out = new PrintWriter(socket.getOutputStream(), true);
//opens a BufferedReader on the socket
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if (printOutput) System.out.println(" Requesting output for the '" + menuSelection + "' command from " + hostName);
// get the current time (before sending the request to the server)
startTime = System.currentTimeMillis();
// send the command to the server
out.println(Integer.toString(menuSelection));
if (printOutput) System.out.println("Sent output");
// read the output from the server
String outputString;
while (((outputString = input.readLine()) != null) && (!outputString.equals("END_MESSAGE"))) {
if (printOutput) System.out.println(outputString);
}
// get the current time (after connecting to the server)
endTime = System.currentTimeMillis();
// endTime - startTime = the time it took to get the response from the sever
totalTime.addAndGet(endTime - startTime);
}
catch (UnknownHostException e) {
System.err.println("Unknown host: " + hostName);
System.exit(1);
}
catch (ConnectException e) {
System.err.println("Connection refused by host: " + hostName);
System.exit(1);
}
catch (IOException e) {
e.printStackTrace();
}
// finally, close the socket and decrement runningThreads
finally {
if (printOutput) System.out.println("closing");
try {
socket.close();
runningThreads.decrementAndGet();
System.out.flush();
}
catch (IOException e ) {
System.out.println("Couldn't close socket");
}
}
}
}
*************************
We will create the directory as server
We will have below classes in it
CommandExecutor.java
Server.java
ServerThread.java
CommandExecutor.java
*******************
******************
Server.java
****************
ServerThread.java
***********************
Please find the below instructions in executing the program
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.