/*   
     WebServer program
     [coded by Arul John] <http://wolf.rules.it>
*/

import java.io.*;
import java.net.*;
import java.util.*;

public class WS {
    public static void main(String args[]) {
    String dataFromClient;
    int count = 0;
	try {
	    // create webserver object
	    ServerSocket ss = new ServerSocket(8000);
	    System.out.println("Server started and running!");
	    Socket s = ss.accept();
	    BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
	    PrintWriter pw = new PrintWriter(s.getOutputStream());
	    int j = 0;
	    while (j < 100) {
		count++;
		System.out.println("New client! Client #" + count);
		String inData = reader.readLine();
		System.out.println("request:" + inData);
		// if no filename is entered, prompt for filename
		if (inData.equals("GET / HTTP/1.1")) {
		    System.out.println("enter a filename");
		    pw.print("Content-type: text/plain\n\n");
		    pw.print("Client says : " + inData);
		} else { // process and show contents of filename
		    StringTokenizer filenames = new StringTokenizer(inData);
		    String filename = filenames.nextToken();
		    filename = filenames.nextToken();
		    String f = "";
		    for (int i = 1; i < filename.length(); i++) {
			f += filename.charAt(i);
		    }
		    System.out.println("filename = " + f);
		    // opening filestreams and input streams
		    FileInputStream fis = new FileInputStream(f);
		    BufferedReader b = new BufferedReader(new InputStreamReader(fis));
		    pw.println("Content-type: text/html\n\n");
		    System.out.println("Content-type: text/html\n\n");
		    String c;
		    while ((c = b.readLine()) != null) {
			pw.print(c);
			System.out.print(c);
		    }
		    fis.close();
		    b.close();
		}
		j++;
		s = ss.accept();
	    }
	    reader.close();
	    pw.close();
	    s.close();
	    ss.close();
	} catch(Exception e) {
	    e.printStackTrace();
	}
    }
}
