import java.io.*; import java.net.*; /** * HttpServer is a simple web server. It supports only the GET method and only * HTML, text, GIF, and JPEG files. */ public class HttpServer { private static int DEFAULT_PORT = 80; private int serverPort; public static void main(String[] args) { int port = DEFAULT_PORT; // Get command-lines arguments. If command-line arg "port" cannot be // converted to an integer, print a usage message and exit. if (args.length >= 1) { try { port = Integer.parseInt(args[0]); } catch(NumberFormatException ex) { System.out.println("Usage: HttpServer [port]"); System.exit(0); } } (new HttpServer(port)).go(); } /** * Constructs a new HttpServer that listens on the default port. */ public HttpServer() { this(DEFAULT_PORT); } /** * Constructs a new HttpServer that listens on the specified port. */ public HttpServer(int port) { super(); this.serverPort = port; } /** * Starts the server. */ public void go() { ServerSocket httpSocket; Socket clientSocket; HttpRequestThread requestThread; try { httpSocket = new ServerSocket(serverPort); System.out.println("HttpServer running on port " + serverPort + "."); try { while (true) { System.out.println("Waiting ..."); // Accept any client connection. clientSocket = httpSocket.accept(); System.out.println("Request received."); // Start a thread to service the client request. requestThread = new HttpRequestThread(clientSocket); requestThread.start(); System.out.println("Request thread started."); } } finally { httpSocket.close(); } } catch(Exception ex) { System.out.println(ex.toString()); } System.exit(0); } }