package jutil; import java.util.*; import java.io.*; import java.net.*; import jutil.*; /** * A simple reusable server. */ public class Server { /** * The server will listen for incoming requests on this socket. */ protected ServerSocket mySocket; /** * The server's port. This is an integer between 0 and 65535. * Ports in the range of 0 through 1023 are reserved for well known * servers. */ protected int myPort; /** * Subclass of RequestHandler to be used for incoming requests. */ protected Class handlerType; /** * Initializes port to 5555. */ public Server() { this(5555); } /** * Initializes port, sets handlerType to RequestHandler. * @param port the port used. */ public Server(int port) { this(port, "jutil.RequestHandler"); } /** * Initializes port and handler type. * @param port The port used * @param htp The name of the request handler subclass. */ public Server(int port, String htp) { try { myPort = port; mySocket = new ServerSocket(myPort); handlerType = Class.forName(htp); } catch(Exception e) { System.err.println("error: " + e.getMessage()); System.exit(1); } // catch } /** * Creates a request handler equipped with a socket connected to * the client. Reflection is used to create handler from the * handler type class. This is a version of the Pluggable Adapter * pattern. * * @param s The server-side socket which is already connected to the client. */ public RequestHandler makeHandler(Socket s) { RequestHandler handler = null; try { handler = (RequestHandler) handlerType.newInstance(); handler.setSocket(s); } catch(Exception e) { System.err.println(e.getMessage()); } return handler; } /** * Perpetually listens for incoming client requests, the spawns a request * handler slave to handle the request. */ public void listen() { System.out.println("server address: " + mySocket.getInetAddress()); try { while(true) { System.out.println("Server listening at port " + myPort); Socket socket = mySocket.accept(); // blocks RequestHandler handler = makeHandler(socket); if (handler == null) continue; Thread slave = new Thread(handler); slave.start(); } // while } catch(IOException ioe) { System.err.println("Failed to accept socket, " + ioe); System.exit(1); } // catch } /** * Users may specify the port and request handler subclass at the command line. * The default port is 5555. The default request handler is RequestHandler. */ public static void main(String[] args) { int port = 5555; String service = "jutil.RequestHandler"; if (1 <= args.length) { port = Integer.parseInt(args[0]); } if (2 <= args.length) { service = args[1]; } Server server = new Server(port, service); server.listen(); } }