SlideShare a Scribd company logo
1 of 6
Download to read offline
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 SMSinforumobile
 
SMS API InforUMobile
SMS API InforUMobileSMS API InforUMobile
SMS API InforUMobileinforumobile
 
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.pdfarccreation001
 
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.pdflakshmijewellery
 
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 referencePragnyaNandaSabat
 
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 .docxfelicidaddinwoodie
 
InfoSMS API for Sending SMS
InfoSMS API for Sending SMSInfoSMS API for Sending SMS
InfoSMS API for Sending SMSinforumobile
 
API למפתחים לערוץ SMS במערכת InforUMobile
API למפתחים לערוץ SMS במערכת InforUMobileAPI למפתחים לערוץ SMS במערכת InforUMobile
API למפתחים לערוץ SMS במערכת InforUMobileinforumobile
 
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 & mailtrapKaty Slemon
 
Socket programming
Socket programmingSocket programming
Socket programmingAnurag 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.docxwilcockiris
 
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.pdfsupport58
 
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 .pdfallisontraders
 
2.communcation in distributed system
2.communcation in distributed system2.communcation in distributed system
2.communcation in distributed systemGd 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.docxrandymartin91030
 
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.docxloganta
 

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.pdfadityacommunications2
 
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.pdfadityacommunications2
 
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.pdfadityacommunications2
 
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.pdfadityacommunications2
 
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.pdfadityacommunications2
 
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 .pdfadityacommunications2
 
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.pdfadityacommunications2
 
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.pdfadityacommunications2
 
Update include ltiostreamgt include ltfstreamgt .pdf
Update  include ltiostreamgt include ltfstreamgt .pdfUpdate  include ltiostreamgt include ltfstreamgt .pdf
Update include ltiostreamgt include ltfstreamgt .pdfadityacommunications2
 
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.pdfadityacommunications2
 
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.pdfadityacommunications2
 
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.pdfadityacommunications2
 
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.pdfadityacommunications2
 
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.pdfadityacommunications2
 
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.pdfadityacommunications2
 
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.pdfadityacommunications2
 
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.pdfadityacommunications2
 
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.pdfadityacommunications2
 
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 .pdfadityacommunications2
 
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.pdfadityacommunications2
 

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

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 

Recently uploaded (20)

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 

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.