// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.*;
import java.util.*;
import java.net.*;

public class WebServer {
   private final static int PORT = 80;
   private final static String PATH = "C:\\";
   public static void main(String[] arg) {
      ServerSocket ss = null;
      try {
         ss = new ServerSocket(PORT);
      } catch (IOException e) {
         System.out.println("Can not bind to port " + PORT);
         System.exit(0);
      }
      while(true) {
         try {
            Socket s = ss.accept();
            InputStream is = s.getInputStream();
            OutputStream os = s.getOutputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            PrintWriter pw = new PrintWriter(os);
            String req = br.readLine();
            StringTokenizer st = new StringTokenizer(req, " ");
            String method = st.nextToken();
            String path = st.nextToken();
            String protocol = st.nextToken();
            if(path.equals("/")) {
               path = "index.htm";
            }
            System.out.println(method + " " + path);
            boolean binary;
            String type;
            if(path.indexOf(".htm") > 0) {
               binary = false;
               type = "text/html";
            } else if(path.indexOf(".txt") > 0) {
               binary = false;
               type = "text/plain";
            } else if(path.indexOf(".gif") > 0) {
               binary = true;
               type = "image/gif";
            } else if(path.indexOf(".jpg") > 0) {
               binary = true;
               type = "image/jpeg";
            } else {
               binary = true;
               type = "application/octet-stream";
            }
            pw.println("HTTP/0.9 200 OK");
            pw.println("Content-Type: " + type);
            pw.println();
            pw.flush();
            os.flush();
            if(binary) {
               sendBinary(path, os);
            } else {
               sendText(path, pw);
            }
            os.flush();
            s.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }
   }
   private static void sendText(String filename, PrintWriter pw) throws IOException {
      BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(PATH + filename)));
      String line;
      while((line = br.readLine()) != null) {
         pw.println(line);
      }
      pw.flush();
   }
   private static void sendBinary(String filename, OutputStream os) throws IOException {
      InputStream is = new FileInputStream(PATH + filename);
      byte[] b = new byte[100000];
      int n;
      while((n = is.read(b)) >= 0){
         os.write(b, 0, n);
      }
   }
}
