tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Socket Programming > Simple Web Server

Simple Web Server 

This turoial shows how to build a prototypic web server using java socket programming. Here the web server is implemented as a stand alone java application with a single java class and client is nothing but the web browser.

File Name  :  
com/bethecoder/tutorials/socketprog/SimpleWebServer.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.socketprog;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleWebServer {

  public static final int DEFAULT_WEB_SERVER_PORT = 6666;
  private int webServerPort = DEFAULT_WEB_SERVER_PORT;
  private int webServerRequestCount = 0;
  private ServerSocket webServerSocket;
  
  public SimpleWebServer(int webServerPort) {
    this.webServerPort = webServerPort;
    this.webServerRequestCount = 0;
  }
  
  /**
   * Start the web server 
   */
  protected void start() {
    
    log("Starting web server on port : " + webServerPort);
    
    try {
      //Web server socket creation
      webServerSocket = new ServerSocket(webServerPort);
      log("Started web server on port : " + webServerPort);
      
      /**
       * Wait for clients
       */
      listen();
      
    catch (Exception e) {
      hault("Error: " + e);
    }
  }
  
  /**
   * Listening on webServerPort for the clients to connect. 
   */
  protected void listen() {
    log("Waiting for connection");
    while (true) {
      try {
        // Got a connection request from client
        Socket client = webServerSocket.accept();
        webServerRequestCount ++;
        
        //Handle client request
        //This processing can be in a separate Thread
        //if we would like to handle multiple requests
        //in parallel.
        serveClient(client);
        
      catch (Exception e) {
        log("Error: " + e);
      }
    }
  }

  protected void serveClient(Socket clientthrows IOException {
    
    /**
     * Read the client request (parse the data if required)
     */
    readClientRequest(client);
    
    /**
     * Send the response back to the client.
     */
    writeClientResponse(client);
  }
  
  protected void readClientRequest(Socket clientthrows IOException {
    
    log("\n--- Request from : " + client + " ---");
    
    /**
     * Read the data sent by client.
     */
    BufferedReader in = new BufferedReader(
          new InputStreamReader(client.getInputStream()));
    
    // read the data sent. We basically ignore it,
    // stop reading once a blank line is hit. This
    // blank line signals the end of the client HTTP
    // headers.
    String str = ".";
    while (!str.equals("")) {
      str = in.readLine();
      log(str);
    }
  }
  
  protected void writeClientResponse(Socket clientthrows IOException {
    PrintWriter out = new PrintWriter(client.getOutputStream());
    // Send the response
    // Send the headers
    out.println("HTTP/1.0 200 OK");
    out.println("Content-Type: text/html");
    out.println("Server: SimpleWebServer");
    // this blank line signals the end of the headers
    out.println("");
    // Send the HTML page
    out.println("<CENTER>");
    out.println("<H1 style='color:red'>Welcome to SimpleWebServer<H1>");
    out.println("<H2>This page has been visited <span style='color:blue'>" 
        webServerRequestCount + " time(s)</span></H2>");
    out.println("</CENTER>");
    out.flush();
    client.close();
  }
  
  private static void log(String msg) {
    System.out.println(msg);
  }
  
  private static void hault(String msg) {
    System.out.println(msg);
    System.exit(0);
  }
  
  public static void main(String args[]) {
    /**
     * Start web server on port '8888'
     */
    SimpleWebServer ws = new SimpleWebServer(8888);
    ws.start();
  }
}
   

It gives the following output in server console,

File Name  :  
source/com/bethecoder/tutorials/socketprog/SimpleWebServer.txt 
Starting web server on port : 8888
Started web server on port : 8888
Waiting for connection

--- Request from : Socket[addr=/127.0.0.1,port=1117,localport=8888] ---
GET / HTTP/1.1
Host: localhost:8888
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Cache-Control: max-age=0


--- Request from : Socket[addr=/127.0.0.1,port=1118,localport=8888] ---
GET / HTTP/1.1
Host: localhost:8888
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Cache-Control: max-age=0


Browser client response is shown below,
simplewebserver


 
  


  
bl  br