/* Program MyWWW.java */

import java.net.*;
import java.io.*;
import java.util.*;

public class MyWWW {
    public static void main(String[] args) throws IOException {


	// creates a new server type socket
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(2000);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 2000.");
            System.exit(1);
        }


        Socket clientSocket = null;
        try {
            clientSocket = serverSocket.accept();
        } catch (IOException e) {
            System.err.println("Accept failed.");
            System.exit(1);
        }

	clientSocket.setSoTimeout(3000);

	// create input and output streams based on the newly
	// created connection.

        PrintWriter out = 
		new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(
				new InputStreamReader(
				clientSocket.getInputStream()));
        String inputLine, outputLine;


	// We will echo the input to the sending client.
        while ((inputLine = in.readLine()) != null) {
             outputLine = inputLine;	// echo only

	     if(inputLine.length() >= 3) {	
	     char[] buf = new char[3];
	     inputLine.getChars(0,3,buf,0);
	     String cmd = new String(buf);
	     if(cmd.equals("GET"))
		processGet(clientSocket);
	     }
	
	     System.out.println(inputLine);
        }
        out.close();
        in.close();
        clientSocket.close();
        serverSocket.close();
    }

    static final byte[] eol = {(byte)'\r', (byte)'\n' };
    static String EOL = new String(eol);

    static void processGet(Socket s) throws IOException {
        PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
        pw.print("HTTP/1.0 " + 200 +" OK");
        pw.write(EOL);
        pw.print("Server: Simple java");
        pw.write(EOL);
        pw.print("Date: " + (new Date()));
        pw.write(EOL);
        pw.print("Content-type: text/html");
        pw.write(EOL);

        try {
            FileInputStream in = new FileInputStream("MyWWW.java");
            PrintStream ps = new PrintStream(s.getOutputStream());

            byte[] buf = new byte[512];
            int count;
            while ((count = in.read(buf)) > 0) {
                ps.write(buf, 0, count);
            }
            pw.write(EOL);
            in.close();
        } 
	catch (IOException e) {  e.printStackTrace(); }

    }

}

