iNET Interactive - Online Advertising Agency
          
   Home    Authors    About    Login    Contact Us
   Search:   
Advanced Search     
  Articles

  ASP (26)
  ASP.NET (19)
  C and C++ (4)
  CFML (2)
  CGI and Perl (16)
  Flash (2)
  Java (7)
  JavaScript (28)
  PHP (92)
  MySQL (13)
  MSSQL (3)
  HTML (35)
  SEO (9)
  Visual Basic (12)
  CSS (13)
  SSI (5)
  XML (12)
  C# (14)

  Developer News

July 4, 2009
US online advertisers scramble to avoid new privacy legislat...
WebDevTips UK
 
July 4, 2009
Massive Bank Fraud In EVE Online
WebDevTips UK
 
July 4, 2009
Amazon Wants Patent For Inserting Ads Into Books
WebDevTips UK
 
July 4, 2009
Mafia Wars Becoming "Cult Classic"
About
 
July 4, 2009
Facebook Privacy and Google
About
 
July 3, 2009
Why Freelancing is Awesome
About
 
Courtesy of moreover.com
 
Want to receive new articles via e-mail? Click here!
/Home /Java

Building a simple HTTP Server using Java 

  Views:    31883
  Votes:    16
by Ahmad Permessur 12/12/03 Rating: 

Synopsis:

This tutorial outlines some basic Java Networking concepts to create a simple HTTP server.
Pages: 
The Article

In this tutorial, we will learn how to create an HTTP server using Java. While Java is mostly known on the Net for its applets on webpage, Java has many networking features including packets, Remote Method Invocation (RMI), and servlets.

 

The documentation on the sun.java.com website is a great way to get your feet wet with some of the basic of Java Networking features. For this tutorial, I will assume that you know how to work with URLs and understand how sockets works. To understand the basic concept of servers, refer to my previous article Web Development Primer.

 

The code for our basic HTTP server is outlined below along with comment tags which explain the different classes.

 

//***************************************
// HTTP Server
//***************************************


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


public class httpServer
{
   
    public static void main(String args[]) {

int port;
ServerSocket server_socket;


try {
    port = Integer.parseInt(args[0]);
}
catch (Exception e) {
    port = 4444;
}


try {
   
   //print out the port number for user
    server_socket = new ServerSocket(port);
    System.out.println("httpServer running on port " +
       server_socket.getLocalPort());
   
    // server infinite loop
    while(true) {
Socket socket = server_socket.accept();
System.out.println("New connection accepted " +
   socket.getInetAddress() +
   ":" + socket.getPort());

// Construct handler to process the HTTP request message.
try {
    httpRequestHandler request =
new httpRequestHandler(socket);
    // Create a new thread to process the request.
    Thread thread = new Thread(request);
   
    // Start the thread.
    thread.start();
}
catch(Exception e) {
    System.out.println(e);
}
    }
}

catch (IOException e) {
    System.out.println(e);
}
    }
}


 
class httpRequestHandler implements Runnable
{
    final static String CRLF = "\r\n";
    Socket socket;
    InputStream input;
    OutputStream output;
    BufferedReader br;

    // Constructor
    public httpRequestHandler(Socket socket) throws Exception
    {
this.socket = socket;
this.input = socket.getInputStream();
this.output = socket.getOutputStream();
this.br =
    new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }
   
    // Implement the run() method of the Runnable interface.
    public void run()
    {
try {
    processRequest();
}
catch(Exception e) {
    System.out.println(e);
}
    }
   
    private void processRequest() throws Exception
    {
while(true) {
   
    String headerLine = br.readLine();
    System.out.println(headerLine);
    if(headerLine.equals(CRLF) || headerLine.equals("")) break;
   
    StringTokenizer s = new StringTokenizer(headerLine);
    String temp = s.nextToken();
   
    if(temp.equals("GET")) {

String fileName = s.nextToken();
fileName = "." + fileName ;

// Open the requested file.
FileInputStream fis = null ;
boolean fileExists = true ;
try
    {
fis = new FileInputStream( fileName ) ;
    }
catch ( FileNotFoundException e )
    {
fileExists = false ;
    }

// Construct the response message.
String serverLine = "Server: fpont simple java httpServer";
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
String contentLengthLine = "error";
if ( fileExists )
    {
statusLine = "HTTP/1.0 200 OK" + CRLF ;
contentTypeLine = "Content-type: " +
    contentType( fileName ) + CRLF ;
contentLengthLine = "Content-Length: "
    + (new Integer(fis.available())).toString()
    + CRLF;
    }
else
    {
statusLine = "HTTP/1.0 404 Not Found" + CRLF ;
contentTypeLine = "text/html" ;
entityBody = "<HTML>" +
    "<HEAD><TITLE>404 Not Found</TITLE></HEAD>" +
    "<BODY>404 Not Found"
    +"<br>usage:http://www.snaip.com:4444/"
    +"fileName.html</BODY></HTML>" ;
    }

// Send the status line.
output.write(statusLine.getBytes());

// Send the server line.
output.write(serverLine.getBytes());

// Send the content type line.
output.write(contentTypeLine.getBytes());

// Send the Content-Length
output.write(contentLengthLine.getBytes());

// Send a blank line to indicate the end of the header lines.
output.write(CRLF.getBytes());

// Send the entity body.
if (fileExists)
    {
sendBytes(fis, output) ;
fis.close();
    }
else
    {
output.write(entityBody.getBytes());
    }

    }
}

try {
    output.close();
    br.close();
    socket.close();
}
catch(Exception e) {}
    }
   
    private static void sendBytes(FileInputStream fis, OutputStream os)
throws Exception
    {
// Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024] ;
int bytes = 0 ;

// Copy requested file into the socket's output stream.
while ((bytes = fis.read(buffer)) != -1 )
    {
os.write(buffer, 0, bytes);
    }
    }
   
    private static String contentType(String fileName)
    {
if (fileName.endsWith(".htm") || fileName.endsWith(".html"))
    {
return "text/html";
    }

return "";

    }
   
}

 

To run this source, copy and paste it in any text editor of your choice and save it as httpServer.java. To compile it, fire up your MS-Dos terminal if you are under Windows or upon a new shell window in Linux. Type javac httpServer.java and hit the return key. When you are done, type java httpServer to run the application.

 

As default, I have used the port 4444. Feel free to change this port. To be able to run your server to fetch html files, save a couple of files in the same directory as your httpServer.java. Use index.html for the directory root file. Open your browser of choice and go to the URL http://localhost:4444/filename.html

Pages: 

Similar/related articles:


 
  Sponsors