// File: TrivialWebServer.java (Module 13) // // Author: Rahul Simha // Created: Nov 30, 2010 // // A trivial webserver that only sends files from a single // directory. import java.net.*; import java.io.*; public class TrivialWebServer { public static void main (String[] argv) { try { // Create a listening service for connections // at the designated port number. ServerSocket srv = new ServerSocket (40013); while (true) { // When a connection is made, get the socket. // The method accept() blocks until then. System.out.println ("Webserver: waiting for a connection"); Socket soc = srv.accept (); // At this stage, the connection will have been made. InetAddress remoteMachine = soc.getInetAddress(); System.out.println ("Accepted a connection from " + remoteMachine); // We are going to both read and write. Start with reading. InputStream inStream = soc.getInputStream (); InputStreamReader isr = new InputStreamReader (inStream); LineNumberReader lnr = new LineNumberReader (isr); // For writing. OutputStream outStream = soc.getOutputStream (); PrintWriter pw = new PrintWriter (outStream); // First read the GET command. String command = lnr.readLine (); // Remove "GET " so that the remainder is the file name. String fileName = command.substring (4); // Now serve the file back. FileReader fr = new FileReader (fileName); LineNumberReader lnr2 = new LineNumberReader (fr); String line = lnr2.readLine (); while (line != null) { pw.println (line); line = lnr2.readLine (); } // Close the streams. pw.close (); lnr.close (); soc.close (); } // end-while } catch (IOException e) { System.out.println (e); } } }