/** * Code is taken from Computer Networking: A Top-Down Approach Featuring * the Internet, second edition, copyright 1996-2002 J.F Kurose and K.W. Ross, * All Rights Reserved. **/ import java.io.*; import java.net.*; import java.util.*; class seqHTTPServer { public static int serverPort = 6789; //public static String WWW_ROOT = "/home/httpd/html/zoo/classes/cs433/"; public static String WWW_ROOT = "./"; public static void main(String args[]) throws Exception { // see if we do not use default server port if (args.length >= 1) serverPort = Integer.parseInt(args[0]); // see if we want a different root if (args.length >= 2) WWW_ROOT = args[1]; // create server socket ServerSocket listenSocket = new ServerSocket(serverPort); System.out.println("server listening at: " + listenSocket); System.out.println("server www root: " + WWW_ROOT); while (true) { try { // take a ready connection from the accepted queue Socket connectionSocket = listenSocket.accept(); System.out.println("receive request from " + connectionSocket); // read the request from client BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); String requestMessageLine; requestMessageLine = inFromClient.readLine(); System.out.println("request line: " + requestMessageLine); // process the request StringTokenizer tokenizedLine = new StringTokenizer(requestMessageLine); if (tokenizedLine.nextToken().equals("GET")) { String urlName; // parse URL to retrieve file name urlName = tokenizedLine.nextToken(); if (urlName.startsWith("/") == true ) urlName = urlName.substring(1); processRequest(urlName, connectionSocket); } // end of if else System.out.println("Bad Request Message"); } catch (Exception e) { } } // end of while (true) } // end of main private static void processRequest(String urlName, Socket connectionSocket) throws Exception { // get output stream DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); // map file name String fileLoc = WWW_ROOT + urlName; System.out.println ("Request: GET " + fileLoc); File file = new File( fileLoc ); if (!file.isFile()) { // generate response header outToClient.writeBytes("HTTP/1.0 404 Not Found\r\n"); } else { int numOfBytes = (int) file.length(); FileInputStream inFile = new FileInputStream (fileLoc); byte[] fileInBytes = new byte[numOfBytes]; inFile.read(fileInBytes); // generate response header outToClient.writeBytes("HTTP/1.0 200 Document Follows\r\n"); if (urlName.endsWith(".jpg")) outToClient.writeBytes("Content-Type: image/jpeg\r\n"); if (urlName.endsWith(".gif")) outToClient.writeBytes("Content-Type: image/gif\r\n"); outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n"); outToClient.writeBytes("\r\n"); // send file content outToClient.write(fileInBytes, 0, numOfBytes); } // close connectionSocket connectionSocket.close(); } // end of processARequest } // end of class WebServer