SlideShare a Scribd company logo
Update the Assignment 3 code to follow the guidelines below it.
Purpose of Assignment 3:
In assignment 3, you're tasked with writing the server-side software for a simple guessing game.
Clients will connect to your server software and guess a random number between 1-99 (inclusive).
If they guess correctly, they receive a congratulations message. If not, they'll be told whether their
guess was too high or too low. They should also have the option to disconnect from the server at
any time.
MY SERVER FOR ASSIGNMENT 3:
package SocketProgramming;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class Assignment3 {
public static void main(String[] args) {
// Create a TCP stream socket bound to 127.0.0.1 and port 7777 to listen for incoming clients
try {
InetAddress ipAddress = InetAddress.getByName("127.0.0.1");
try (ServerSocket serverSocket = new ServerSocket(7777, 0, ipAddress)) {
// Loop forever to listen for connections
while (true) {
// Accept an incoming connection, creating a socket for that client
Socket clientSocket = serverSocket.accept();
// Generate a random integer from 1 to 99 code(inclusive)
Random randomNum = new Random();
int answer = randomNum.nextInt(99) + 1;
// Send a 'hello' message to the client
String message = "hellorn";
OutputStream outputStream = clientSocket.getOutputStream();
outputStream.write(message.getBytes());
// Loop forever to receive new messages from this client
while (true) {
// Receive an incoming message and decode it using ASCII encoding
InputStream inputStream = clientSocket.getInputStream();
byte[] buffer = new byte[1024];
int numBytesReceived = inputStream.read(buffer);
String textReceived = new String(buffer, 0, numBytesReceived, "ASCII");
// If the message is a 'quit' message, disconnect from this client and start listening again
if (textReceived.equals("quitrn")) {
clientSocket.close();
break;
}
// If the message is a 'guess' message, parse the client's guess, then...
else if (textReceived.startsWith("guesst")) {
String guessString = textReceived.substring(6);
// ...If their guess matches the answer, send a 'correct' message to them and disconnect from the
client
if (Integer.parseInt(guessString) == answer) {
String response = "correctrn";
outputStream.write(response.getBytes());
clientSocket.close();
break;
}
// ...If their guess is greater than the answer, send a 'too-high' message and continue listening
else if (Integer.parseInt(guessString) > answer) {
String response = "too-highrn";
outputStream.write(response.getBytes());
}
// ...If their guess is less than the answer, send a 'too-low' message and continue listening
else {
String response = "too-lowrn";
outputStream.write(response.getBytes());
}
}
}
}
}
} catch (Exception e) {
System.err.println("An error occurred: " + e.getMessage());
}
}
}
THE CLIENT FOR ASSIGNMENT 3:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
// Written in C# using .NET 7.0
// Note: This program intentionally does not perform exception handling
// This will allow you to more easily diagnose issues with your
connection and protocol
public static class Assignment3 {
public static void Main() {
Client();
}
private static void Client() {
// Create a TCP stream socket local to this computer using port 7777
var ipAddress = IPAddress.Parse("127.0.0.1");
var remoteEp = new IPEndPoint(ipAddress, 7777);
using var sender = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
sender.Connect(remoteEp);
// The server must initially send the client a 'hello' message upon
connection
var buffer = new byte[1024];
var numBytesReceived = sender.Receive(buffer);
var textReceived = Encoding.ASCII.GetString(buffer, 0,
numBytesReceived);
// If the server does not respond with the 'hello' message, terminate
the program
if (textReceived != "hellorn") {
Console.WriteLine("Server is not ready yet");
return;
}
// Loop forever to receive user input
for (; ; ) {
// Allow the user to guess a number, or an empty string to quit
Console.Write("Enter your guess (leave empty to disconnect): ");
var input = Console.ReadLine();
string message;
if (string.IsNullOrWhiteSpace(input)) {
// If the user's input was empty, our message to the server
will be a 'quit' message
input = null;
message = "quitrn";
}
else if (int.TryParse(input, out int guess)) {
// If the user entered a valid integer, our message will be
a 'guess' message
message = string.Format("guesst{0}rn", input);
}
else {
// If the user entered anything else, make them to try
again
Console.WriteLine("Invalid input");
continue;
}
// Send the ASCII encoded message to the server
var bytes = Encoding.ASCII.GetBytes(message);
sender.Send(bytes);
// If the user didn't enter anything, the client can safely
disconnect and end the program
if (input == null) {
break;
}
// Receive a response from the server and decode it using ASCII
encoding
numBytesReceived = sender.Receive(buffer);
textReceived = Encoding.ASCII.GetString(buffer, 0,
numBytesReceived);
// If the server responded with a 'correct' message, tell the
user they won and stop the loop
if (textReceived == "correctrn") {
Console.WriteLine("Congratulations! You won!");
break;
}
// The server should have responded with either a 'too-high' or
'too-low' message as a hint
else {
Console.WriteLine("Incorrect guess. Here's a hint: {0}",
textReceived.TrimEnd());
}
}
// Shut down the connection to the server
sender.Shutdown(SocketShutdown.Both);
}
private static void Server() {
throw new NotImplementedException("Create the server software by
following these steps for Assignment 3");
// Create a TCP stream socket bound to 127.0.0.1 and port 7777 to
listen for incoming clients
// Loop forever to listen for connections
// Accept an incoming connection, creating a socket for that client
// Generate a random integer from 1 to 99 (inclusive)
// Send a 'hello' message to the client
// Loop forever to receive new messages from this client
// Receive an incoming message and decode it using ASCII
encoding
// If the message is a 'quit' message, disconnect from this
client and start listening again
// If the message is a 'guess' message, parse the client's
guess, then...
// ...If their guess matches the answer, send a
'correct' message to them and disconnect from the client
// ...If their guess is greater than the answer, send a
'too-high' message and continue listening
// ...If their guess is less than the answer, send a
'too-low' message and continue listening
}
}
WHAT I NEED TO DO:
In this assignment, you're tasked with updating your client/server program from Assignment 3 to
include server-side records. This is a common practice for client/server applications since both
clients and the server can benefit from record-keeping. Servers have a reliable log of client activity
while clients can access useful information stored on the trusted server. This program should have
the same functionality as Assignment 3 with added features related to record keeping. Unlike
Assignment 3, you will have to write your own client software in addition to the server software. If
you think it will help, you're welcome to use the provided client code from Assignment 3 as a
starting point. You are allowed and encouraged to re-use any code you wrote for Assignment 3.1.
The client should prompt the user for their desired username before initiating any connection with
the server. Make sure to trim whitespace from the name. You're welcome to impose other
restrictions on usernames if you'd like (hint: maybe disallow commas if you're using CSV
formatting on the server!). 2. The server should maintain an external file (txt, csv, etc.) which
contains each user's 'high score' for the guessing game. For this exercise, we consider users to be
identifiable solely by their username from Task 1. Their 'high score' is the minimum number of
guesses taken to win the guessing game. 3. When a client connects to the server, the server
should send it a 'hello' message (same as Assignment 3). The client should respond with a 'user'
message which contains their desired username. The server should respond with a 'welcome'
message which contains either this user's current high score or -1 if the server doesn't recognize
this user. Any deviation from this initial handshake should result in the client's disconnection from
the server. 4. When the client receives a 'welcome' message, parse the score argument. If it's -1 ,
print a message to the console welcoming the client to the game for the first time. Otherwise,
welcome them back and print what their previous high score was. 5. When the server sends a
'correct' message to a client, update the record file if necessary. No update is required if that user
did not beat their high score. 6. When the client receives a 'correct' message, print a message to
the console either congratulating them on setting a new high score, beating their previous high
score, or encouraging them to try again to beat their high score (all clients should fall into one of
these three categories) Note: When the server receives a 'quit' message from a first-time client,
you can either choose to 1) Not enter that client into the file at all, since they didn't finish a game,
or 2) enter something into your file to denote that the user quit, then modify Task III to handle the
case of known clients who don't have a high score ASCII Encoding should be used for all
messages|Server -> Client: Client - Server: This application is server-authoritative. This means
that the correct answer should never be explicitly sent to the client. The server should determine if
a client's guess is correct or not and send the appropriate response. You can use your computer's
local IP address 127.0.0.1 and the port 7777. Make sure your server software is running before
you try testing your client software, otherwise it won't have anything to connect to! Check your
firewall settings if the connection still cannot be made.

More Related Content

Similar to Update the Assignment 3 code to follow the guidelines below .pdf

InfoSMS API for Sending SMS
InfoSMS API for Sending SMSInfoSMS API for Sending SMS
InfoSMS API for Sending SMS
inforumobile
 
SMS API InforUMobile
SMS API InforUMobileSMS API InforUMobile
SMS API InforUMobile
inforumobile
 
vishal_sharma: python email sending software
vishal_sharma: python email sending software  vishal_sharma: python email sending software
vishal_sharma: python email sending software
vishal sharma
 
How a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdfHow a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdf
arccreation001
 
I have a simple TCP clientserver socket set up in Python. How can I.pdf
I have a simple TCP clientserver socket set up in Python. How can I.pdfI have a simple TCP clientserver socket set up in Python. How can I.pdf
I have a simple TCP clientserver socket set up in Python. How can I.pdf
lakshmijewellery
 
9271736-Parasitic-computing.ppt for students reference
9271736-Parasitic-computing.ppt for students reference9271736-Parasitic-computing.ppt for students reference
9271736-Parasitic-computing.ppt for students reference
PragnyaNandaSabat
 
17 Spring 2018 Assignment 3 Chat server .docx
17   Spring 2018 Assignment 3 Chat server .docx17   Spring 2018 Assignment 3 Chat server .docx
17 Spring 2018 Assignment 3 Chat server .docx
felicidaddinwoodie
 
InfoSMS API for Sending SMS
InfoSMS API for Sending SMSInfoSMS API for Sending SMS
InfoSMS API for Sending SMS
inforumobile
 
API למפתחים לערוץ SMS במערכת InforUMobile
API למפתחים לערוץ SMS במערכת InforUMobileAPI למפתחים לערוץ SMS במערכת InforUMobile
API למפתחים לערוץ SMS במערכת InforUMobile
inforumobile
 
Node mailer example how to send email using nodemailer with gmail & mailtrap
Node mailer example how to send email using nodemailer with gmail & mailtrapNode mailer example how to send email using nodemailer with gmail & mailtrap
Node mailer example how to send email using nodemailer with gmail & mailtrap
Katy Slemon
 
Socket programming
Socket programmingSocket programming
Socket programming
Anurag Tomar
 
import java.util.Scanner;Henry Cutler ID 1234 7202.docx
import java.util.Scanner;Henry Cutler ID 1234  7202.docximport java.util.Scanner;Henry Cutler ID 1234  7202.docx
import java.util.Scanner;Henry Cutler ID 1234 7202.docx
wilcockiris
 
Please help with the below 3 questions, the python script is at the.pdf
Please help with the below 3  questions, the python script is at the.pdfPlease help with the below 3  questions, the python script is at the.pdf
Please help with the below 3 questions, the python script is at the.pdf
support58
 
TCPIP Client Server program exampleHere is a simple example of .pdf
TCPIP Client Server program exampleHere is a simple example of .pdfTCPIP Client Server program exampleHere is a simple example of .pdf
TCPIP Client Server program exampleHere is a simple example of .pdf
allisontraders
 
2.communcation in distributed system
2.communcation in distributed system2.communcation in distributed system
2.communcation in distributed system
Gd Goenka University
 
Please look at the attach See.doc. I am getting this error all th.docx
Please look at the attach See.doc. I am getting this error all th.docxPlease look at the attach See.doc. I am getting this error all th.docx
Please look at the attach See.doc. I am getting this error all th.docx
randymartin91030
 
Chapter 4--converted.pptx
Chapter 4--converted.pptxChapter 4--converted.pptx
Chapter 4--converted.pptx
WijdenBenothmen1
 
OverviewIn this project you will implement a server for the Purdue.docx
OverviewIn this project you will implement a server for the Purdue.docxOverviewIn this project you will implement a server for the Purdue.docx
OverviewIn this project you will implement a server for the Purdue.docx
loganta
 

Similar to Update the Assignment 3 code to follow the guidelines below .pdf (20)

InfoSMS API for Sending SMS
InfoSMS API for Sending SMSInfoSMS API for Sending SMS
InfoSMS API for Sending SMS
 
SMS API InforUMobile
SMS API InforUMobileSMS API InforUMobile
SMS API InforUMobile
 
vishal_sharma: python email sending software
vishal_sharma: python email sending software  vishal_sharma: python email sending software
vishal_sharma: python email sending software
 
How a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdfHow a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdf
 
I have a simple TCP clientserver socket set up in Python. How can I.pdf
I have a simple TCP clientserver socket set up in Python. How can I.pdfI have a simple TCP clientserver socket set up in Python. How can I.pdf
I have a simple TCP clientserver socket set up in Python. How can I.pdf
 
9271736-Parasitic-computing.ppt for students reference
9271736-Parasitic-computing.ppt for students reference9271736-Parasitic-computing.ppt for students reference
9271736-Parasitic-computing.ppt for students reference
 
17 Spring 2018 Assignment 3 Chat server .docx
17   Spring 2018 Assignment 3 Chat server .docx17   Spring 2018 Assignment 3 Chat server .docx
17 Spring 2018 Assignment 3 Chat server .docx
 
InfoSMS API for Sending SMS
InfoSMS API for Sending SMSInfoSMS API for Sending SMS
InfoSMS API for Sending SMS
 
API למפתחים לערוץ SMS במערכת InforUMobile
API למפתחים לערוץ SMS במערכת InforUMobileAPI למפתחים לערוץ SMS במערכת InforUMobile
API למפתחים לערוץ SMS במערכת InforUMobile
 
Node mailer example how to send email using nodemailer with gmail & mailtrap
Node mailer example how to send email using nodemailer with gmail & mailtrapNode mailer example how to send email using nodemailer with gmail & mailtrap
Node mailer example how to send email using nodemailer with gmail & mailtrap
 
Internet
InternetInternet
Internet
 
Socket programming
Socket programmingSocket programming
Socket programming
 
import java.util.Scanner;Henry Cutler ID 1234 7202.docx
import java.util.Scanner;Henry Cutler ID 1234  7202.docximport java.util.Scanner;Henry Cutler ID 1234  7202.docx
import java.util.Scanner;Henry Cutler ID 1234 7202.docx
 
Please help with the below 3 questions, the python script is at the.pdf
Please help with the below 3  questions, the python script is at the.pdfPlease help with the below 3  questions, the python script is at the.pdf
Please help with the below 3 questions, the python script is at the.pdf
 
TCPIP Client Server program exampleHere is a simple example of .pdf
TCPIP Client Server program exampleHere is a simple example of .pdfTCPIP Client Server program exampleHere is a simple example of .pdf
TCPIP Client Server program exampleHere is a simple example of .pdf
 
2.communcation in distributed system
2.communcation in distributed system2.communcation in distributed system
2.communcation in distributed system
 
Please look at the attach See.doc. I am getting this error all th.docx
Please look at the attach See.doc. I am getting this error all th.docxPlease look at the attach See.doc. I am getting this error all th.docx
Please look at the attach See.doc. I am getting this error all th.docx
 
Isup
IsupIsup
Isup
 
Chapter 4--converted.pptx
Chapter 4--converted.pptxChapter 4--converted.pptx
Chapter 4--converted.pptx
 
OverviewIn this project you will implement a server for the Purdue.docx
OverviewIn this project you will implement a server for the Purdue.docxOverviewIn this project you will implement a server for the Purdue.docx
OverviewIn this project you will implement a server for the Purdue.docx
 

More from adityacommunications2

US Civilian Labor Force Participation Rate Civlian Unemplo.pdf
US Civilian Labor Force Participation Rate Civlian Unemplo.pdfUS Civilian Labor Force Participation Rate Civlian Unemplo.pdf
US Civilian Labor Force Participation Rate Civlian Unemplo.pdf
adityacommunications2
 
US set to lift covid19 testing requirements for travelers f.pdf
US set to lift covid19 testing requirements for travelers f.pdfUS set to lift covid19 testing requirements for travelers f.pdf
US set to lift covid19 testing requirements for travelers f.pdf
adityacommunications2
 
URINARY SYSTEMI Nephron COLORING EXERCISE part it Draw a.pdf
URINARY SYSTEMI Nephron COLORING EXERCISE part it  Draw a.pdfURINARY SYSTEMI Nephron COLORING EXERCISE part it  Draw a.pdf
URINARY SYSTEMI Nephron COLORING EXERCISE part it Draw a.pdf
adityacommunications2
 
US Civilian Labor Force Participation Rate Cilitian Unempl.pdf
US Civilian Labor Force Participation Rate Cilitian Unempl.pdfUS Civilian Labor Force Participation Rate Cilitian Unempl.pdf
US Civilian Labor Force Participation Rate Cilitian Unempl.pdf
adityacommunications2
 
US Civilian Labor Force Participation Rate Cillian Unemplo.pdf
US Civilian Labor Force Participation Rate Cillian Unemplo.pdfUS Civilian Labor Force Participation Rate Cillian Unemplo.pdf
US Civilian Labor Force Participation Rate Cillian Unemplo.pdf
adityacommunications2
 
Urgent Draw the EER diagram for the Hiking Database given .pdf
Urgent  Draw the EER diagram for the Hiking Database given .pdfUrgent  Draw the EER diagram for the Hiking Database given .pdf
Urgent Draw the EER diagram for the Hiking Database given .pdf
adityacommunications2
 
Upan denetic analysis ot the canceromis tissue a mutated fo.pdf
Upan denetic analysis ot the canceromis tissue a mutated fo.pdfUpan denetic analysis ot the canceromis tissue a mutated fo.pdf
Upan denetic analysis ot the canceromis tissue a mutated fo.pdf
adityacommunications2
 
UPS prides itself on having uptodate information on the pr.pdf
UPS prides itself on having uptodate information on the pr.pdfUPS prides itself on having uptodate information on the pr.pdf
UPS prides itself on having uptodate information on the pr.pdf
adityacommunications2
 
Update include ltiostreamgt include ltfstreamgt .pdf
Update  include ltiostreamgt include ltfstreamgt .pdfUpdate  include ltiostreamgt include ltfstreamgt .pdf
Update include ltiostreamgt include ltfstreamgt .pdf
adityacommunications2
 
Underground Sandwiches a sandwich shop has the following m.pdf
Underground Sandwiches a sandwich shop has the following m.pdfUnderground Sandwiches a sandwich shop has the following m.pdf
Underground Sandwiches a sandwich shop has the following m.pdf
adityacommunications2
 
Understand processivity and fidelity Indicate if a given enz.pdf
Understand processivity and fidelity Indicate if a given enz.pdfUnderstand processivity and fidelity Indicate if a given enz.pdf
Understand processivity and fidelity Indicate if a given enz.pdf
adityacommunications2
 
Unlike the theory of international trade or the theory of in.pdf
Unlike the theory of international trade or the theory of in.pdfUnlike the theory of international trade or the theory of in.pdf
Unlike the theory of international trade or the theory of in.pdf
adityacommunications2
 
Unemployment which is when persons in an economy have lost.pdf
Unemployment  which is when persons in an economy have lost.pdfUnemployment  which is when persons in an economy have lost.pdf
Unemployment which is when persons in an economy have lost.pdf
adityacommunications2
 
Unknown case study2 Your patient is a 26 yo male who presen.pdf
Unknown case study2 Your patient is a 26 yo male who presen.pdfUnknown case study2 Your patient is a 26 yo male who presen.pdf
Unknown case study2 Your patient is a 26 yo male who presen.pdf
adityacommunications2
 
Una moneda justa se lanza seis veces Cul es la probabilid.pdf
Una moneda justa se lanza seis veces Cul es la probabilid.pdfUna moneda justa se lanza seis veces Cul es la probabilid.pdf
Una moneda justa se lanza seis veces Cul es la probabilid.pdf
adityacommunications2
 
Una persona con diabetes T2 debe tratar de controlar los car.pdf
Una persona con diabetes T2 debe tratar de controlar los car.pdfUna persona con diabetes T2 debe tratar de controlar los car.pdf
Una persona con diabetes T2 debe tratar de controlar los car.pdf
adityacommunications2
 
Una forma principal en la que los genes tienen un efecto sob.pdf
Una forma principal en la que los genes tienen un efecto sob.pdfUna forma principal en la que los genes tienen un efecto sob.pdf
Una forma principal en la que los genes tienen un efecto sob.pdf
adityacommunications2
 
Una fuerte correlacin entre A y B implicara que B es causa.pdf
Una fuerte correlacin entre A y B implicara que B es causa.pdfUna fuerte correlacin entre A y B implicara que B es causa.pdf
Una fuerte correlacin entre A y B implicara que B es causa.pdf
adityacommunications2
 
Unit 11 Forum 6 6 unread replies 6 6 replies Find a video .pdf
Unit 11 Forum 6 6 unread replies 6 6 replies Find a video .pdfUnit 11 Forum 6 6 unread replies 6 6 replies Find a video .pdf
Unit 11 Forum 6 6 unread replies 6 6 replies Find a video .pdf
adityacommunications2
 
Una enfermera est cuidando a un cliente adulto mayor La e.pdf
Una enfermera est cuidando a un cliente adulto mayor La e.pdfUna enfermera est cuidando a un cliente adulto mayor La e.pdf
Una enfermera est cuidando a un cliente adulto mayor La e.pdf
adityacommunications2
 

More from adityacommunications2 (20)

US Civilian Labor Force Participation Rate Civlian Unemplo.pdf
US Civilian Labor Force Participation Rate Civlian Unemplo.pdfUS Civilian Labor Force Participation Rate Civlian Unemplo.pdf
US Civilian Labor Force Participation Rate Civlian Unemplo.pdf
 
US set to lift covid19 testing requirements for travelers f.pdf
US set to lift covid19 testing requirements for travelers f.pdfUS set to lift covid19 testing requirements for travelers f.pdf
US set to lift covid19 testing requirements for travelers f.pdf
 
URINARY SYSTEMI Nephron COLORING EXERCISE part it Draw a.pdf
URINARY SYSTEMI Nephron COLORING EXERCISE part it  Draw a.pdfURINARY SYSTEMI Nephron COLORING EXERCISE part it  Draw a.pdf
URINARY SYSTEMI Nephron COLORING EXERCISE part it Draw a.pdf
 
US Civilian Labor Force Participation Rate Cilitian Unempl.pdf
US Civilian Labor Force Participation Rate Cilitian Unempl.pdfUS Civilian Labor Force Participation Rate Cilitian Unempl.pdf
US Civilian Labor Force Participation Rate Cilitian Unempl.pdf
 
US Civilian Labor Force Participation Rate Cillian Unemplo.pdf
US Civilian Labor Force Participation Rate Cillian Unemplo.pdfUS Civilian Labor Force Participation Rate Cillian Unemplo.pdf
US Civilian Labor Force Participation Rate Cillian Unemplo.pdf
 
Urgent Draw the EER diagram for the Hiking Database given .pdf
Urgent  Draw the EER diagram for the Hiking Database given .pdfUrgent  Draw the EER diagram for the Hiking Database given .pdf
Urgent Draw the EER diagram for the Hiking Database given .pdf
 
Upan denetic analysis ot the canceromis tissue a mutated fo.pdf
Upan denetic analysis ot the canceromis tissue a mutated fo.pdfUpan denetic analysis ot the canceromis tissue a mutated fo.pdf
Upan denetic analysis ot the canceromis tissue a mutated fo.pdf
 
UPS prides itself on having uptodate information on the pr.pdf
UPS prides itself on having uptodate information on the pr.pdfUPS prides itself on having uptodate information on the pr.pdf
UPS prides itself on having uptodate information on the pr.pdf
 
Update include ltiostreamgt include ltfstreamgt .pdf
Update  include ltiostreamgt include ltfstreamgt .pdfUpdate  include ltiostreamgt include ltfstreamgt .pdf
Update include ltiostreamgt include ltfstreamgt .pdf
 
Underground Sandwiches a sandwich shop has the following m.pdf
Underground Sandwiches a sandwich shop has the following m.pdfUnderground Sandwiches a sandwich shop has the following m.pdf
Underground Sandwiches a sandwich shop has the following m.pdf
 
Understand processivity and fidelity Indicate if a given enz.pdf
Understand processivity and fidelity Indicate if a given enz.pdfUnderstand processivity and fidelity Indicate if a given enz.pdf
Understand processivity and fidelity Indicate if a given enz.pdf
 
Unlike the theory of international trade or the theory of in.pdf
Unlike the theory of international trade or the theory of in.pdfUnlike the theory of international trade or the theory of in.pdf
Unlike the theory of international trade or the theory of in.pdf
 
Unemployment which is when persons in an economy have lost.pdf
Unemployment  which is when persons in an economy have lost.pdfUnemployment  which is when persons in an economy have lost.pdf
Unemployment which is when persons in an economy have lost.pdf
 
Unknown case study2 Your patient is a 26 yo male who presen.pdf
Unknown case study2 Your patient is a 26 yo male who presen.pdfUnknown case study2 Your patient is a 26 yo male who presen.pdf
Unknown case study2 Your patient is a 26 yo male who presen.pdf
 
Una moneda justa se lanza seis veces Cul es la probabilid.pdf
Una moneda justa se lanza seis veces Cul es la probabilid.pdfUna moneda justa se lanza seis veces Cul es la probabilid.pdf
Una moneda justa se lanza seis veces Cul es la probabilid.pdf
 
Una persona con diabetes T2 debe tratar de controlar los car.pdf
Una persona con diabetes T2 debe tratar de controlar los car.pdfUna persona con diabetes T2 debe tratar de controlar los car.pdf
Una persona con diabetes T2 debe tratar de controlar los car.pdf
 
Una forma principal en la que los genes tienen un efecto sob.pdf
Una forma principal en la que los genes tienen un efecto sob.pdfUna forma principal en la que los genes tienen un efecto sob.pdf
Una forma principal en la que los genes tienen un efecto sob.pdf
 
Una fuerte correlacin entre A y B implicara que B es causa.pdf
Una fuerte correlacin entre A y B implicara que B es causa.pdfUna fuerte correlacin entre A y B implicara que B es causa.pdf
Una fuerte correlacin entre A y B implicara que B es causa.pdf
 
Unit 11 Forum 6 6 unread replies 6 6 replies Find a video .pdf
Unit 11 Forum 6 6 unread replies 6 6 replies Find a video .pdfUnit 11 Forum 6 6 unread replies 6 6 replies Find a video .pdf
Unit 11 Forum 6 6 unread replies 6 6 replies Find a video .pdf
 
Una enfermera est cuidando a un cliente adulto mayor La e.pdf
Una enfermera est cuidando a un cliente adulto mayor La e.pdfUna enfermera est cuidando a un cliente adulto mayor La e.pdf
Una enfermera est cuidando a un cliente adulto mayor La e.pdf
 

Recently uploaded

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 

Recently uploaded (20)

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 

Update the Assignment 3 code to follow the guidelines below .pdf

  • 1. Update the Assignment 3 code to follow the guidelines below it. Purpose of Assignment 3: In assignment 3, you're tasked with writing the server-side software for a simple guessing game. Clients will connect to your server software and guess a random number between 1-99 (inclusive). If they guess correctly, they receive a congratulations message. If not, they'll be told whether their guess was too high or too low. They should also have the option to disconnect from the server at any time. MY SERVER FOR ASSIGNMENT 3: package SocketProgramming; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.Random; public class Assignment3 { public static void main(String[] args) { // Create a TCP stream socket bound to 127.0.0.1 and port 7777 to listen for incoming clients try { InetAddress ipAddress = InetAddress.getByName("127.0.0.1"); try (ServerSocket serverSocket = new ServerSocket(7777, 0, ipAddress)) { // Loop forever to listen for connections while (true) { // Accept an incoming connection, creating a socket for that client Socket clientSocket = serverSocket.accept(); // Generate a random integer from 1 to 99 code(inclusive) Random randomNum = new Random(); int answer = randomNum.nextInt(99) + 1; // Send a 'hello' message to the client String message = "hellorn"; OutputStream outputStream = clientSocket.getOutputStream(); outputStream.write(message.getBytes()); // Loop forever to receive new messages from this client while (true) { // Receive an incoming message and decode it using ASCII encoding InputStream inputStream = clientSocket.getInputStream(); byte[] buffer = new byte[1024]; int numBytesReceived = inputStream.read(buffer); String textReceived = new String(buffer, 0, numBytesReceived, "ASCII"); // If the message is a 'quit' message, disconnect from this client and start listening again if (textReceived.equals("quitrn")) { clientSocket.close();
  • 2. break; } // If the message is a 'guess' message, parse the client's guess, then... else if (textReceived.startsWith("guesst")) { String guessString = textReceived.substring(6); // ...If their guess matches the answer, send a 'correct' message to them and disconnect from the client if (Integer.parseInt(guessString) == answer) { String response = "correctrn"; outputStream.write(response.getBytes()); clientSocket.close(); break; } // ...If their guess is greater than the answer, send a 'too-high' message and continue listening else if (Integer.parseInt(guessString) > answer) { String response = "too-highrn"; outputStream.write(response.getBytes()); } // ...If their guess is less than the answer, send a 'too-low' message and continue listening else { String response = "too-lowrn"; outputStream.write(response.getBytes()); } } } } } } catch (Exception e) { System.err.println("An error occurred: " + e.getMessage()); } } } THE CLIENT FOR ASSIGNMENT 3: using System; using System.Net; using System.Net.Sockets; using System.Text; // Written in C# using .NET 7.0 // Note: This program intentionally does not perform exception handling // This will allow you to more easily diagnose issues with your connection and protocol public static class Assignment3 {
  • 3. public static void Main() { Client(); } private static void Client() { // Create a TCP stream socket local to this computer using port 7777 var ipAddress = IPAddress.Parse("127.0.0.1"); var remoteEp = new IPEndPoint(ipAddress, 7777); using var sender = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); sender.Connect(remoteEp); // The server must initially send the client a 'hello' message upon connection var buffer = new byte[1024]; var numBytesReceived = sender.Receive(buffer); var textReceived = Encoding.ASCII.GetString(buffer, 0, numBytesReceived); // If the server does not respond with the 'hello' message, terminate the program if (textReceived != "hellorn") { Console.WriteLine("Server is not ready yet"); return; } // Loop forever to receive user input for (; ; ) { // Allow the user to guess a number, or an empty string to quit Console.Write("Enter your guess (leave empty to disconnect): "); var input = Console.ReadLine(); string message; if (string.IsNullOrWhiteSpace(input)) { // If the user's input was empty, our message to the server will be a 'quit' message input = null; message = "quitrn"; } else if (int.TryParse(input, out int guess)) { // If the user entered a valid integer, our message will be a 'guess' message message = string.Format("guesst{0}rn", input); } else { // If the user entered anything else, make them to try again
  • 4. Console.WriteLine("Invalid input"); continue; } // Send the ASCII encoded message to the server var bytes = Encoding.ASCII.GetBytes(message); sender.Send(bytes); // If the user didn't enter anything, the client can safely disconnect and end the program if (input == null) { break; } // Receive a response from the server and decode it using ASCII encoding numBytesReceived = sender.Receive(buffer); textReceived = Encoding.ASCII.GetString(buffer, 0, numBytesReceived); // If the server responded with a 'correct' message, tell the user they won and stop the loop if (textReceived == "correctrn") { Console.WriteLine("Congratulations! You won!"); break; } // The server should have responded with either a 'too-high' or 'too-low' message as a hint else { Console.WriteLine("Incorrect guess. Here's a hint: {0}", textReceived.TrimEnd()); } } // Shut down the connection to the server sender.Shutdown(SocketShutdown.Both); } private static void Server() { throw new NotImplementedException("Create the server software by following these steps for Assignment 3"); // Create a TCP stream socket bound to 127.0.0.1 and port 7777 to listen for incoming clients // Loop forever to listen for connections // Accept an incoming connection, creating a socket for that client // Generate a random integer from 1 to 99 (inclusive) // Send a 'hello' message to the client // Loop forever to receive new messages from this client
  • 5. // Receive an incoming message and decode it using ASCII encoding // If the message is a 'quit' message, disconnect from this client and start listening again // If the message is a 'guess' message, parse the client's guess, then... // ...If their guess matches the answer, send a 'correct' message to them and disconnect from the client // ...If their guess is greater than the answer, send a 'too-high' message and continue listening // ...If their guess is less than the answer, send a 'too-low' message and continue listening } } WHAT I NEED TO DO: In this assignment, you're tasked with updating your client/server program from Assignment 3 to include server-side records. This is a common practice for client/server applications since both clients and the server can benefit from record-keeping. Servers have a reliable log of client activity while clients can access useful information stored on the trusted server. This program should have the same functionality as Assignment 3 with added features related to record keeping. Unlike Assignment 3, you will have to write your own client software in addition to the server software. If you think it will help, you're welcome to use the provided client code from Assignment 3 as a starting point. You are allowed and encouraged to re-use any code you wrote for Assignment 3.1. The client should prompt the user for their desired username before initiating any connection with the server. Make sure to trim whitespace from the name. You're welcome to impose other restrictions on usernames if you'd like (hint: maybe disallow commas if you're using CSV formatting on the server!). 2. The server should maintain an external file (txt, csv, etc.) which contains each user's 'high score' for the guessing game. For this exercise, we consider users to be identifiable solely by their username from Task 1. Their 'high score' is the minimum number of guesses taken to win the guessing game. 3. When a client connects to the server, the server should send it a 'hello' message (same as Assignment 3). The client should respond with a 'user' message which contains their desired username. The server should respond with a 'welcome' message which contains either this user's current high score or -1 if the server doesn't recognize this user. Any deviation from this initial handshake should result in the client's disconnection from the server. 4. When the client receives a 'welcome' message, parse the score argument. If it's -1 , print a message to the console welcoming the client to the game for the first time. Otherwise, welcome them back and print what their previous high score was. 5. When the server sends a 'correct' message to a client, update the record file if necessary. No update is required if that user did not beat their high score. 6. When the client receives a 'correct' message, print a message to the console either congratulating them on setting a new high score, beating their previous high score, or encouraging them to try again to beat their high score (all clients should fall into one of these three categories) Note: When the server receives a 'quit' message from a first-time client,
  • 6. you can either choose to 1) Not enter that client into the file at all, since they didn't finish a game, or 2) enter something into your file to denote that the user quit, then modify Task III to handle the case of known clients who don't have a high score ASCII Encoding should be used for all messages|Server -> Client: Client - Server: This application is server-authoritative. This means that the correct answer should never be explicitly sent to the client. The server should determine if a client's guess is correct or not and send the appropriate response. You can use your computer's local IP address 127.0.0.1 and the port 7777. Make sure your server software is running before you try testing your client software, otherwise it won't have anything to connect to! Check your firewall settings if the connection still cannot be made.