We are currently performing maintenance on our servers, you may experience some connection errors. We apologize for any inconvenience.

Sign In/My Account | View Cart  


AddThis Social Bookmark Button

Email.Email article link
The Java Cookbook (cover)

Java Recipe of the Day

The following recipe is from The Java Cookbook, by Ian Darwin. All links in this recipe point to the online version of the book on the Safari Bookshelf.

Buy it now, or read it online on the Safari Bookshelf.

17.5. Serving the HTTP Protocol

. Discussion

This example just constructs a ServerSocket and listens on it. When connections come in, they are replied to using the HTTP protocol. So it is somewhat more involved than the simple Echo server presented in Recipe 17.2. However, it's not a complete web server; the filename in the request is ignored, and a standard message is always returned. This is thus a very simple web server; it follows only the bare minimum of the HTTP protocol needed to send its response back. A somewhat more complete example is presented in Recipe 24.8, after the issues of multithreading have been covered. For a real web server written in Java, get Tomcat from http://jakarta.apache.org/tomcat/. The code shown in Example 17-8, however, is enough to understand how to structure a simple server that communicates using a protocol.

Example 8. WebServer0.java

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

 * A very very very simple Web server.
 * There is only one response to all requests, and it's hard-coded.
 * This version is not threaded and doesn't do very much.
 * Really just a proof of concept.
 * However, it is still useful on notebooks in case somebody connects
 * to you on the Web port by accident (or otherwise).
 * Can't claim to be fully standards-conforming, but has been
 * tested with Netscape Communicator and with the Lynx text browser.
 * @author    Ian Darwin, http://www.darwinsys.com/
 * @version    $Id: ch17.xml,v 1.4 2004/05/04 18:04:54 ian Exp $
 * @see        webserver/* for more fully-fleshed-out version(s).
public class WebServer0 {
    public static final int HTTP = 80;
    ServerSocket s;

     * Main method, just creates a server and call its runServer(  ).
    public static void main(String[] argv) throws Exception {
        System.out.println("DarwinSys JavaWeb Server 0.0 starting...");
        WebServer0 w = new WebServer0(  );
        w.runServer(HTTP);        // never returns!!

    /** Get the actual ServerSocket; deferred until after Constructor
     * so subclass can mess with ServerSocketFactory (e.g., to do SSL).
     * @param port The port number to listen on
    protected ServerSocket getServerSocket(int port) throws Exception {
        return new ServerSocket(port);

    /** RunServer accepts connections and passes each one to handler. */
    public void runServer(int port) throws Exception {
        s = getServerSocket(port);
        while (true) {
            try {
                Socket us = s.accept(  );
            } catch(IOException e) {


    /** Handler(  ) handles one conversation with a Web client.
     * This is the only part of the program that "knows" HTTP.
    public void Handler(Socket s) {
        BufferedReader is;    // inputStream, from Viewer
        PrintWriter os;        // outputStream, to Viewer
        String request;        // what Viewer sends us.
        try {
            String from = s.getInetAddress().toString(  );
            System.out.println("Accepted connection from " + from);
            is = new BufferedReader(new InputStreamReader(s.getInputStream(  )));
            request = is.readLine(  );
            StringTokenizer st = new StringTokenizer(request);
            System.out.println(""Request: " + request);
            String nullLine = is.readLine(  );
            os = new PrintWriter(s.getOutputStream(  ), true);
            os.println("HTTP/1.0 200 Here is your data");
            os.println("Content-type: text/html");
            os.println("Server-name: DarwinSys NULL Java WebServer 0");
            String reply = "<html><head>" +
                "<title>Wrong System Reached</title></head>\n" +
                "<h1>Welcome, " + from + ", but...</h1>\n" +
                "<p>You have reached a desktop machine " +
                "that does not run a real Web service.\n" +
                "<p>Please pick another system!</p>\n" +
                "<p>Or view <A HREF=\"http://www.darwinsys.com/java/server.html\">" +
                "the WebServer0 source (at the Authors Web Site)</A>.</p>\n" +
                "<hr/><em>Java-based WebServer0</em><hr/>\n" +
            os.println("Content-length: " + reply.length(  ));
            os.flush(  );
            s.close(  );
        } catch (IOException e) {
            System.out.println("IOException " + e);

View the past week's recipes: Today | Yesterday | 3 days ago | 4 days ago | 5 days ago | 6 days ago | A week ago