import java.io.*; import java.net.*; import java.util.*; public class webserver { static final short WPORT = 8008; public static void main(String[] args) { ServerSocket sfd; // listening socket Socket cfd; // communication socket try { sfd = new ServerSocket(WPORT,16); sfd.setReuseAddress(true); while (true) { cfd = sfd.accept(); // wait for client connection service(cfd); cfd.close(); } // while } catch (IOException e) {e.printStackTrace();} } // main private static void service(Socket cfd) throws IOException { String oneline = ""; String word = ""; InetAddress clientaddr = cfd.getInetAddress(); System.out.println("connection from "+clientaddr); BufferedReader scin = new BufferedReader(new InputStreamReader(cfd.getInputStream())); PrintWriter scout = new PrintWriter(new OutputStreamWriter(cfd.getOutputStream())); StringTokenizer st; // for parsing BufferedReader fin; // for reading local file // read 'GET' from client oneline = scin.readLine(); st = new StringTokenizer(oneline); while (!word.equals("GET")) word = st.nextToken(" :/"); // read address of homepage: word = st.nextToken(); if (word.equals("HTTP")) word = "index.html"; else if (!word.substring(0,6).equals("/home/")) word = word.substring(7,word.length()); else word = word.substring(1,word.length()); // at this point, word is the file name we need to load. // open stream to local file: try // in case file doesn't exist { fin = new BufferedReader(new FileReader(word)); } catch (IOException ee) // default { fin = new BufferedReader(new FileReader("index.html")); word = "index.html"; } // catch System.out.println("file "+word+" opened"); // send OK to client scout.print("HTTP/1.1 200 OK\n\0"); scout.flush(); // serve file to client while (oneline != null) { oneline = fin.readLine(); System.out.println(oneline); if (oneline != null) scout.print(oneline+"\n"); } scout.flush(); fin.close(); scin.close(); scout.close(); }// service } // class webserver