Very simple Java http server

I’m learning to build a simple Java http server. This is the first working version (raw and unpolished).

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;

public class Conexion extends Thread {
	Socket socket;
	String contentType="";
	String filename;
	String header;
	File returnfile;
	long filelength;

	Conexion(Socket socket) {
	    this.socket = socket;
	  }
	public void run() {
	    try {
	    	BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
	    	PrintWriter out = new PrintWriter(socket.getOutputStream());
	        if (in!=null) getClientHeader(in);
	        System.out.println("File: "+filename);
	        System.out.println("Content type: "+contentType);

	        // show file requested
	        returnfile=new File(filename);

	        System.out.println("\nClient requested:" + returnfile.getAbsolutePath() + "\n");
	        // get file lenght
	        filelength= returnfile.length();
	        // try to open the file
	        FileInputStream requestedfile = null;
	        try {

	          requestedfile = new FileInputStream(filename);
	          header=constructHttpServerHeader(200);
		      out.write(header);
		      int databyte = requestedfile.read();
		      System.out.println("***BEGIN DATA***");
		      while (databyte!=-1) {
		          //read the file from filestream, and print out through the
		          //client-outputstream on a byte per byte base.
		    	  out.write(databyte);
		    	  System.out.print(databyte);
		          databyte = requestedfile.read();
		      }
		      out.println("\r\n");
		      System.out.println("***END DATA***");
		          out.flush();
		          //clean up the files
		          out.close();
		          requestedfile.close();
	        }
	        catch (Exception e) {
	            //if you could not open the file send a 404
	            header=constructHttpServerHeader(404);
	            out.println(header);
	            //close the stream
	            out.close();
	          }
	        socket.close();
	    } catch (IOException e) {
	      System.out.println(e);
	    }
	  }
	//only returns the GET line
	public void getClientHeader(BufferedReader in) {
		String inputstr = ".";
        try {
        	System.out.println("***BEGIN CLIENT HEADER***");
        	while (!inputstr.equals("")) {
				inputstr = in.readLine();
				System.out.println(inputstr);
				if (inputstr!=null) {
				if (inputstr.startsWith("GET")) { 
					// search filename
				    int start = 0;
				    int end = 0;
				    for (int a = 0; a < inputstr.length(); a++) {
				      if (inputstr.charAt(a) == ' ' && start != 0) {
				        end = a;
				        break;
				        }
				        if (inputstr.charAt(a) == ' ' && start == 0) {
				          start = a;
				        }
				      }
				      filename = inputstr.substring(start + 2, end); //fill in the path
				      // Get the content type
				      contentType="html"; // default mime type
				      if (filename.endsWith(".zip")) {
				         contentType = "zip";
				       }
				       if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) {
				         contentType = "jpg";
				       }
				       if (filename.endsWith(".gif")) {
				         contentType = "gif";
				       }
				       if (filename.endsWith(".png")) {
					     contentType = "png";
					   }

				} // end if
				} // end if null
			} // end while
        	System.out.println("***END CLIENT HEADER***");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println(e);
		}
	}

	private String constructHttpServerHeader(int return_code) {
	    String s = "HTTP/1.0 ";
	    switch (return_code) {
	      case 200:
	        s = s + "200 OK";
	        break;
	      case 400:
	        s = s + "400 Bad Request";
	        break;
	      case 403:
	        s = s + "403 Forbidden";
	        break;
	      case 404:
	        s = s + "404 Not Found";
	        break;
	      case 500:
	        s = s + "500 Internal Server Error";
	        break;
	      case 501:
	        s = s + "501 Not Implemented";
	        break;
	    }

	    s = s + "\r\n"; //other header fields,
	    s = s + "Content-Length: " + filelength +"\r\n";
	    s = s + "Accept-Ranges: bytes\r\n";
	    s = s + "Connection: close\r\n"; //we can't handle persistent connections
	    s = s + "Server: localhost \r\n"; //server name
	    switch (contentType) {
	      //plenty of types for you to fill in
	      case "jpg":
	        s = s + "Content-Type: image/jpeg\r\n";
	        break;
	      case "gif":
	        s = s + "Content-Type: image/gif\r\n";
	        break;
	      case "zip":
	        s = s + "Content-Type: application/x-zip-compressed\r\n";
	        break;
	      case "png":
		    s = s + "Content-Type: image/png\r\n";
		    break;
	      default:
	        s = s + "Content-Type: text/html\r\n";
	        break;
	    }
	    s = s + "\r\n"; //this marks the end of the httpheader (blank line)
	    System.out.println("***BEGIN SERVER HEADER***");
	    System.out.print(s);
	    System.out.println("***END SERVER HEADER***");
	    return s;
	  }

}
import java.net.ServerSocket;
import java.net.Socket;

public class Httpsvr
{
	  public static void main(String args[]) throws Exception {
	    ServerSocket ssock = new ServerSocket(1234);
	    System.out.println("Listening");
	    while (true) {
	      Socket sock = ssock.accept();
	      System.out.println("Client connected.");
	      new Conexion(sock).start();
	    }
	  }

}
Posted in In progress, Internet, Java, Programming Tagged with: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*