7. Modify the EchoServer.java code to enable the server to serve each connection
ID: 3869976 • Letter: 7
Question
7. Modify the EchoServer.java code to enable the server to serve each connection in a separate thread. That is, make the server multi-threaded.
8. Allow the multi-threaded server to stop accepting new requests when any of the active clients sends the message ‘stop’. In addition, the server should terminate when all clients have exited by waiting for the threads to finish
8 public class EchoServer 10 public EchoServer (int portnum) try 12 13 14 15 16 17 18 19 20 21 server -new ServerSocket (portnum); catch (Exception err) System.out.println (err); 23 24 25 26 27 28 29 30 31 32 public void serve () try while (true) Socket client server.accept ) System.out.println ("Received a connection from:"+ client.getRemoteSocketAddress ) toStringO) 34 35 36 37 38 39 40 4 1 BufferedReader r - new BufferedReader (new InputStreamReader (client.getInputStream))) PrintWriter w= new PrintWriter (client.getoutputstream(), true); w.printin ("Welcome to the Java EchoServer. Type 'bye to close.") string 1ine; do line- r.readLine nuExplanation / Answer
1. Before do-while loop create a new thread for the client connection as follows:
Thread t = new Thread(new ClientConn(client));
t.start();
Now all the remaining communication for this client will be in separate thread..
2. For server to stop accepting new requests when any of the active clients sends the message ‘stop’ update condition check in do-while as below:
do{
}while (!line.trim().equals(“stop”)).
To stop the server after all the clients have exited, add following method ‘stop’ in the class EchoServer with below lines:
try {
this.server.close();
} catch (IOException e) {
throw new RuntimeException("ERROR Closing server", e);
}
Call this function after try-catch block in serve method in the end.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.