Total members 10259 | Gratitudes |It is currently Mon May 21, 2012 4:02 pm Login / Join Codemiles


All times are UTC [ DST ]




Post new topic Reply to topic  Quick reply  [ 1 post ] 
Author Topic
 Topic subject: HTTP Server in Java
PostPosted: Thu Oct 16, 2008 7:27 pm 
Offline
Mastermind
User avatar

Joined: Tue Mar 27, 2007 10:55 pm
Posts: 2277
Location: Earth
Has thanked: 39 time
Have thanks: 61 time

* Project Name:   HTTP Server in Java
* Programmer:   Abhishek K. Dhote
* Type:   Network
* Technology:  Java
* IDE:   Any
* Description:   This is the implementation of Hyper Text Transfer Protocol in Java.This program can be use as sever which is able to process requsts for HTML pages.

To execute the program using LOCALHOST follow the steps:-
1.install HttpServer.java on one system
2.configure your browser using following steps:
a.go to Tools
b.go to Internet Options...
c.go to Connections
d.go to Lan Setting
e.select Use a proxy server for your lan
f.make Address: http://localhost & Port:100
3.run HttpServer.java
4.run browser
5.put filename.html into the bin of jdk
5.place a request using following format:-
http://localhost.filename.html/
where filename.html is the name of the file you
want to request.


Code:
//HttpServer.java
import java.io.*;
import java.net.*;
import java.util.*;
import java.lang.*;


public class HttpServer
{
     public static void main(String [] args)
     {
          int i=1;

System.out.println("******************************************************
**************************");
          System.out.println("******************************  HTTP
SERVER
***********************************");

System.out.println("******************************************************
**************************");
          System.out.println("Server Started...");
          System.out.println("Waiting for connections...");
          try
          {

               ServerSocket s = new ServerSocket(100);
               for(;;)
               {
                    Socket incoming = s.accept();
                    System.out.println("New Client Connected with id "
+ i
+" from "+incoming.getInetAddress().getHostName() );
                    System.out.println("
");
                    System.out.println("
REQUEST HEADER                                    ");
                    Thread t = new ThreadedServer(incoming,i);
                    i++;
                    t.start();
               }
          }
          catch(Exception e)
          {
               System.out.println("Error: " + e);
          }
     }
}

class ThreadedServer extends Thread
{
     final static String CRLF = "
";
     Socket incoming;
     int counter;
     public ThreadedServer(Socket i,int c)
     {
          incoming=i;
          counter=c;
     }

     public void run()
     {
          try
          {
               String statusline=null;
               String contenttypeline=null;
               String contentlength=null;
               String venderline="Server: EXECUTER 1.1";
               String entitybody=null;
               BufferedReader in =new BufferedReader(new
InputStreamReader(incoming.getInputStream()));
               PrintWriter out = new
PrintWriter(incoming.getOutputStream(), true);
               OutputStream output=incoming.getOutputStream();
               String headerline;
               headerline=in.readLine();
               System.out.println(headerline);
               /*String reqh;

               boolean done=false;
               while(!done)
               {
                    reqh=in.readLine();
                    if(reqh == null)
                         done = true;
                    else
                    {
                         //out.println("Server>>> " + headerline);
                         System.out.println(reqh);
                    }
               }

*/

            StringTokenizer s = new StringTokenizer(headerline);
          String meth = s.nextToken();
               if(meth.equals("GET")||meth.equals("POST"))
               {
                int dot1,dot2,fslash;
                String fname,ext,FileName;
                String url = s.nextToken();

                dot1=url.indexOf('.');
                dot2=url.lastIndexOf('.');
      fslash=url.lastIndexOf('/');
        fname=url.substring(dot1+1,dot2);
                ext=url.substring(dot2,fslash);
                FileName=fname+ext;
//    System.out.println("FNAME:"+FileName);
                if(ext.equals(".html")||ext.equals(".htm"))
                {
                 FileInputStream fis=null;
                 boolean filexists=true;
                 try
                   {
                    fis=new FileInputStream(FileName);
                   }
                 catch(FileNotFoundException e)
                   {
                    System.out.println("Exception: "+e.getMessage());
                    filexists=false;
                   }



                if(filexists)
                {
                 statusline=" HTTP/1.1 200 Ok"+CRLF;
                 contenttypeline="Content-Type: text/html "+CRLF;
                 contentlength="Content-Length:"+(new
Integer(fis.available())).toString() + CRLF;
                }
                else
                {

       statusline = "HTTP/1.0 404 Not Found" + CRLF ;
       contenttypeline = "Content-Type: text/html"+CRLF ;
       entitybody = "<HTML>" +
             "<HEAD><TITLE>404 Not Found</TITLE></HEAD>" +
             "<BODY><H1>404 File Not Found</H1></BODY></HTML>" ;
                }

/*                System.out.println("
RESPONCE HEADER                                    ");

                System.out.println(statusline);
                System.out.println(venderline);
                System.out.println(contentlength);
                System.out.println(contenttypeline);*/

                 output.write(statusline.getBytes());
                 output.write(venderline.getBytes());
                 output.write(contentlength.getBytes());
                 output.write(contenttypeline.getBytes());
                 output.write(CRLF.getBytes());


                 if (filexists)
          {
         sendBytes(fis, output) ;
         fis.close();
          }
      else
          {
         output.write(entitybody.getBytes());
          }

                }
                else
               {
                 statusline = "HTTP/1.0 400 Not Found" + CRLF ;
       contenttypeline = "Content-Type: text/html"+CRLF ;
       entitybody = "<HTML>" +
             "<HEAD><TITLE>400</TITLE></HEAD>" +
             "<BODY><H1>400 A malformed HTTP request is
reived</H1></BODY></HTML>";
               }

               }

                else
                 {
                  statusline = "HTTP/1.0 400 Not Found" + CRLF ;
        contenttypeline = "Content-Type: text/html"+CRLF ;
        entitybody = "<HTML>" +
             "<HEAD><TITLE>400</TITLE></HEAD>" +
                  "<BODY><H1>400 A malformed HTTP request is
reived</H1></BODY></HTML>";
                 }

         boolean done=false;
         while(!done)
         {
          headerline=in.readLine();
          if(headerline == null)
           done = true;
          else
          {
           System.out.println(headerline);
          }
         }

         incoming.close();
         in.close();
         out.close();
          }
          catch(Exception e)
          {
               System.out.println("Error: " + e);
          }
     }
private static void sendBytes(FileInputStream fis, OutputStream os)
   throws Exception
    {
   byte[] buffer = new byte[1024] ;
   int bytes = 0 ;

   while ((bytes = fis.read(buffer)) != -1 )
       {
      os.write(buffer, 0, bytes);
       }
    }


}




Author email : abhishekdhote@rediffmail.com

_________________
Currenlty programming with : java , html , php , and javascript . (OCJP-6 certified )


TOP
 Profile Send private message  
Reply with quote  
Post new topic Reply to topic Quick reply  [ 1 post ] 
Quick reply


  


 Similar topics
 video chat application in java
 navigating to database using java
 java mobile apps
 need help in java
 Read your gmail using Java code
 how to connect client on one machine with server
 Java Programing to communicating port parallel
 Java Chat
 Steganography in java
 java code for listing folder contents from remote folder

All times are UTC [ DST ]


Users browsing similar posts

Users browsing this forum: No registered users and 1 guest



Jump to:  
Previous Topic | Next Topic 




Home
General Talks
Finished Projects
Code Library
Games
Tutorials

Java
C/C++
C-sharp
php
Script
JSP/Servlets
Ajax
ASP/ASP.net
Google SEO
Database
Communications
Phpbb3 styles
Photoshop tutorials
Flash tutorials
Find a job






Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team