package rmi.rmiSynth;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;

public class WebServer {
  public static void main(String args[]) {
    WebServer ws = new WebServer(8080);
  }

  WebServer(int port) {
    try {
      ServerSocket ss
          = new ServerSocket(port);
      while (true) {
        startClient(ss.accept());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void startClient(Socket s)
      throws IOException {
    ClientThread
        ct = new ClientThread(s);
    Thread t = new Thread(ct);
    t.start();
  }
}

class ClientThread implements
    Runnable {
  Socket s;
  BufferedReader br;
  PrintWriter pw;
  public static final String
      notFoundString =
      "HTTP/1.0 501 Not Implemented\n"
      + "Content-type: text/plain\n\n";
  public static final String
      okString =
      "HTTP/1.0 200 OK\n"
      + "Content-type: text/gui.html\n\n";


  ClientThread(Socket _s) {
    s = _s;
    try {
      br =
          new BufferedReader(
              new InputStreamReader(
                  s.getInputStream()));
      pw =
          new PrintWriter(
              s.getOutputStream(), true);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public void run() {
    try {
      String line =
          br.readLine();
      StringTokenizer
          st =
          new StringTokenizer(
              line);
      System.out.println(line);
      if (st.nextToken().equals("GET"))
        countTo10();
      else
        pw.println(notFoundString);
      pw.close();
      s.close();
    } catch (Exception e) {
    }
  }

  public void countTo10() {
    pw.println("HTTP/1.0 200 OK");
    pw.println("Content-type: text/plain");
    pw.println();
    for (int i = 0; i < 10; i++)
      pw.println("i=" + i);
  }

  public void getAFile(StringTokenizer st)
      throws FileNotFoundException,
      IOException {
    pw.println(okString);
    String fileName
        = st.nextToken();
    pw.println("date=" + new java.util.Date());
    BufferedReader
        fileReader = new
            BufferedReader(new
                FileReader(
                    "d:\\www\\" + fileName));
    String fileLine = null;
    while (
        (fileLine =
        fileReader.readLine())
        != null)
      pw.println(fileLine);
  }
}