Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

A Multithreaded HTTP Server

There's one improvement that is customary in servers, and we will make it here. For all but the smallest of servers, it is usual to spawn a new thread to handle each request. This has three big advantages:

  1. Foremost, it makes the server scalable. The server can accept new requests independent of its speed in handling them. (Of course, you better buy a server that has the mippage to keep up with requests.)

  2. By handling each request in a new thread, clients do not have to wait for every request ahead of them to be served.

  3. The program source can be better organized, as the server processing is written in a different class.

The following code demonstrates how we would modify our HTTP web server to a new thread for each client request. The first step is to make another child in the One_Connection hierarchy to implement the Runnable interface. Give it a run method that will actually do all the work: get the request, then send the file.

import java.io.*;
import java.net.*;
class OneConnection_C extends OneConnection_B 
           implements Runnable { 

  OneConnection_C(Socket sock) throws Exception {

  public void run() {
   try {
    String filename = getRequest();
   } catch (Exception e) {
    System.out.println("Excpn: " + e);}


The main program will have the server socket and it will put the accept in a loop (so that we can handle many requests, not just the first one). It will instantiate our connection class as before, turn it into a thread, and invoke its start method. The code follows:

public class HTTPServer4 {
  public static void main(String a[]) throws Exception {

    final int httpd = 80;
    ServerSocket ssock = new ServerSocket(httpd);
    while (true) {
      Socket sock = ssock.accept();
      System.out.println("client has made socket connection");
      OneConnection_C client = new OneConnection_C(sock);
      new Thread(client).start();

The code seems so brief because we have draped the functionality across several classes in an inheritance hierarchy. That was done so that the example code would be smaller and easier to present. You should try putting the code back into one or two classes. It's still only 50 or 60 lines long. This has got to be the world record for the smallest HTTP server.

  • + Share This
  • 🔖 Save To Your Account