package jutil; import java.io.*; import java.net.*; import jutil.*; /** * Base class of all request handler slaves. */ public class RequestHandler extends Correspondent implements Runnable { /** * Set this flag to false in the response method override in order to * stop the handler. */ protected boolean more = true; /** * This constructor does not initialize inherited fields. The * user must subsequently call setSocket. We need this constructor * so the server can use newInstance. */ public RequestHandler() {} /** * Initializes all fields using provided socket. * @param s The socket provided by the server. */ public RequestHandler(Socket s) { super(s); } /** * Initialize all fields using the socket provided. * @param s The socket provided by the server. */ public void setSocket(Socket s) { sock = s; initStreams(); } /** * Override this method in a subclass. The default implementation * merely appends the client message to the string "echo: ". * @param msg The client's message. */ protected String response(String msg) { return "echo: " + msg; } /** * Perpetually receives a message from the client, creates * a response, then sends the response back to the client. * If the message is "quit" then the handler shuts down. */ public void run() { while(more) { String msg = receive(); System.out.println("received: " + msg); //if (msg == null) continue; if (msg.equals("quit")) break; msg = response(msg); System.out.println("sending: " + msg); send(msg); } close(); System.out.println("request handler shutting down"); } }