Friday, July 27, 2012

Example of A Simple HTTP Server In Java


import java.io.*;
import java.util.*;
import java.net.*;

/* This code opens a PFINET TCP socket and listens over port 5000 - to communicate - see following
    client code or simply open a browser and go to http://localhost:5000  which should return HTTP OK code = 200 -> try to figure out how to generate the various error codes below for fun!! */

/* compile this code as follows:  javac myHTTPServer.java
                            then to run it:  java myHTTPServer
                                    To test:  open browser and go to http://localhost:5000  */

public class myHTTPServer extends Thread implements Runnable{


static final String HTML_START =
"" +
"HTTP Server in java" +
"";

static final String HTML_END =
"" +
   "";

  /** http://www.w3.org/Protocols/rfc2616/rfc2616.html **/
  /** 2XX: generally "OK" */
  public static final int HTTP_OK = 200;
  public static final int HTTP_CREATED = 201;
  public static final int HTTP_ACCEPTED = 202;
  public static final int HTTP_NOT_AUTHORITATIVE = 203;
  public static final int HTTP_NO_CONTENT = 204;
  public static final int HTTP_RESET = 205;
  public static final int HTTP_PARTIAL = 206;

  /** 3XX: relocation/redirect */
  public static final int HTTP_MULT_CHOICE = 300;
  public static final int HTTP_MOVED_PERM = 301;
  public static final int HTTP_MOVED_TEMP = 302;
  public static final int HTTP_SEE_OTHER = 303;
  public static final int HTTP_NOT_MODIFIED = 304;
  public static final int HTTP_USE_PROXY = 305;

 /** 4XX: client error */
  public static final int HTTP_BAD_REQUEST = 400;
  public static final int HTTP_UNAUTHORIZED = 401;
  public static final int HTTP_PAYMENT_REQUIRED = 402;
  public static final int HTTP_FORBIDDEN = 403;
  public static final int HTTP_NOT_FOUND = 404;
  public static final int HTTP_BAD_METHOD = 405;
  public static final int HTTP_NOT_ACCEPTABLE = 406;
  public static final int HTTP_PROXY_AUTH = 407;
  public static final int HTTP_CLIENT_TIMEOUT = 408;
  public static final int HTTP_CONFLICT = 409;
  public static final int HTTP_GONE = 410;
  public static final int HTTP_LENGTH_REQUIRED = 411;
  public static final int HTTP_PRECON_FAILED = 412;
  public static final int HTTP_ENTITY_TOO_LARGE = 413;
  public static final int HTTP_REQ_TOO_LONG = 414;
  public static final int HTTP_UNSUPPORTED_TYPE = 415;

  /** 5XX: server error */
  public static final int HTTP_SERVER_ERROR = 500;
  public static final int HTTP_INTERNAL_ERROR = 501;
  public static final int HTTP_BAD_GATEWAY = 502;
  public static final int HTTP_UNAVAILABLE = 503;
  public static final int HTTP_GATEWAY_TIMEOUT = 504;
  public static final int HTTP_VERSION = 505;


int count = 0;

/* create server socket here */

     Socket conn = null;
     BufferedReader inFromClient = null;
     DataOutputStream outToClient = null;

     public myHTTPServer (Socket client)
     {
         conn = client;
         count = 0;
     }

     public void sendFile(FileInputStream fin, DataOutputStream out) throws Exception {
    byte[] buffer = new byte[1024];
    int bytesRead;

    while ((bytesRead = fin.read(buffer)) != -1)
    {
out.write(buffer, 0, bytesRead);
}
fin.close();
}

     public void sendResponse (int statusCode, String resp, boolean isFile) throws Exception
     {

String statusLine = null;
String serverdetails = "Server: Java HTTPServer";
String contentLengthLine = null;
String fileName = null;
String contentTypeLine = "Content-Type: text/html" + "\r\n";
FileInputStream fin = null;

/* expand this code by providing a handler for each of the error codes above - this example only handles
    error code 200 success, 404 file not found, and 400 bad request  */

if (statusCode == 200) {
statusLine = "HTTP/1.1 200 OK" + "\r\n";
}
else if (statusCode == 404){
statusLine = "HTTP/1.1 404 Not Found" + "\r\n";
}
else {
statusLine = "HTTP/1.1 400 Bad Request" + "\r\n";
}

/* expand this if loop to add support for additional file extensions. */

         if (isFile)
         {
fileName = "c:" + "\\" + resp;
//System.out.println("fName: " + fileName);
fin = new FileInputStream(fileName);
System.out.println("isThere: " + fin.available());
contentLengthLine = "Content-Length: " + Integer.toString(fin.available()) + "\r\n";
if (!fileName.endsWith(".htm") && !fileName.endsWith(".html"))
   contentTypeLine = "Content-Type: \r\n";
if (fileName.endsWith(".jpg"))
   contentTypeLine = "Content-Type: image/jpeg\r\n";
if (fileName.endsWith(".gif"))
   contentTypeLine = "Content-Type: image/gif\r\n";
if (fileName.endsWith(".bmp"))
   contentTypeLine = "Content-Type: image/bmp\r\n";
if (fileName.endsWith(".txt"))
   contentTypeLine = "Content-Type: text/html\r\n";
if (fileName.endsWith(".exe"))
   contentTypeLine = "Content-Type: application/octet-stream";
if (fileName.endsWith(".wav"))
   contentTypeLine = "Content-Type: audio/x-wav";

System.out.println("Setting ContentTypeLine To: " + contentTypeLine);
}
else
{
           resp = myHTTPServer.HTML_START + resp + myHTTPServer.HTML_END;
           contentLengthLine = "Content-Length: " + resp.length() + "\r\n";
    }

outToClient.writeBytes(statusLine);
outToClient.writeBytes(serverdetails);
outToClient.writeBytes(contentTypeLine);
outToClient.writeBytes(contentLengthLine);
outToClient.writeBytes("Connection: close\r\n");
outToClient.writeBytes("\r\n");

if (isFile) sendFile(fin, outToClient);
         else outToClient.writeBytes(resp);

outToClient.close();
}

/*start the listener - can also implement this with worker threads */

     public void run()
     {

try {

conn.getInetAddress();
conn.getPort();


inFromClient = new BufferedReader(new InputStreamReader (conn.getInputStream()));
outToClient = new DataOutputStream(conn.getOutputStream());

String request = inFromClient.readLine();
String header = request;
System.out.println("-------");
System.out.println("Thread PID: " + this.getId() );
System.out.println("Server Received: " + header);
StringTokenizer tok = new StringTokenizer(header);
String httpMeth = tok.nextToken();
System.out.println("METHOD: " + httpMeth);
String httpQuery = tok.nextToken();

StringBuffer response = new StringBuffer();

/* customize your own response message here !! */

response.append("Hello!!");
response.append("Goodbye");
response.append("RFC2616 HTTP Spec");
response.append("Sample Web Server Code");
response.append("By Swati Kher
");



while (inFromClient.ready())
{
response.append(request + "
");
System.out.println(request);
    request = inFromClient.readLine();
}

              /** http://www.w3.org/Protocols/rfc2616/rfc2616.html **/
              /** Response Message - refer to rfc2616 for more information!! **/
if (httpMeth.equals("GET"))
{
                if (httpQuery.equals("/"))
                {
 //sendResponse(HTTP_OK, "SWATI KHER PAGE", false);
 sendResponse(HTTP_OK, response.toString(), false);
   }
   else
   {
String fileN = httpQuery.replaceFirst("/", "");
fileN = URLDecoder.decode(fileN);
fileN = "\\" + fileN;
System.out.println("Send File: " + fileN);
//System.out.println("Found: " + (new File(fileN).isFile()));
if (new File(fileN).isFile()) {
sendResponse(HTTP_OK, fileN, true);
   }
else {
sendResponse(HTTP_BAD_REQUEST, "404 Requested file not found", false);
}
}
}
else
{
   sendResponse(HTTP_NOT_FOUND, "400 Resource not found", false);
}

} catch (Exception e)
{
e.printStackTrace();
}
}


     public static void main(String[] args) throws Exception {

ServerSocket Serv = new ServerSocket (5000, 10, InetAddress.getByName("127.0.0.1"));
System.out.println("Server is listening on port 5000...");

while (true) {
 Socket con = Serv.accept();
 (new myHTTPServer(con)).start();
 }
}
}

No comments: