Java Consider the following server code. Can it serve multiple clients properly?
ID: 3824192 • Letter: J
Question
Java
Consider the following server code. Can it serve multiple clients properly? If yes, why. If no, why not, and suggest your solution (with pseudo code).
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
jta.append("Server started at " + new Date() + ' ');
// Listen for a connection request
Socket socket = serverSocket.accept();
// Create data input and output streams
DataInputStream inputFromClient = new DataInputStream(
socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(
socket.getOutputStream());
while (true) {
// Receive radius from the client
double radius = inputFromClient.readDouble();
// Compute area
double area = radius * radius * Math.PI;
// Send area back to the client
outputToClient.writeDouble(area);
jta.append("Radius received from client: " + radius + ' ');
jta.append("Area found: " + area + ' ');
}
}
catch(IOException ex) {
System.err.println(ex);
}
}
Explanation / Answer
NO. Because it accepts a single client and then goes into an infinite while loop which will stop only when an
IoException occurs.
So it cannot handle multiple clients properly.
In order to handle multiple clients we can just change position of while loop like following:
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
jta.append("Server started at " + new Date() + ' ');
while(True)
{
// Listen for a connection request
Socket socket = serverSocket.accept();
// Create data input and output streams
DataInputStream inputFromClient = new DataInputStream(
socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(
socket.getOutputStream());
// Receive radius from the client
double radius = inputFromClient.readDouble();
// Compute area
double area = radius * radius * Math.PI;
// Send area back to the client
outputToClient.writeDouble(area);
jta.append("Radius received from client: " + radius + ' ');
jta.append("Area found: " + area + ' ');
}
}
catch(IOException ex) {
System.err.println(ex);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.