Adding Threading to a Server

The last two programs could only handle one client at a time. That wasn't so much of a problem for HelloServer because it had only a very brief interaction with each client. However the EchoServer might hang on to a connection indefinitely. In this case, it's better to make your server multi-threaded. There should be a loop which continually accepts new connections. However, rather than handling the connection directly the Socket should be passed to a Thread object that handles the connection.

The following example is a threaded echo program.

import java.net.*;
import java.io.*;


public class ThreadedEchoServer extends Thread {

  public final static int defaultPort = 2347;
  Socket theConnection;
  
  public static void main(String[] args) {
  
    int port = defaultPort;
    
    try {
      port = Integer.parseInt(args[0]);
    }
    catch (Exception ex) {
    }
    if (port <= 0 || port >= 65536) port = defaultPort;
    
    try {
      ServerSocket ss = new ServerSocket(port);
      while (true) {
        try {
          Socket s = ss.accept();
          ThreadedEchoServer tes = new ThreadedEchoServer(s);
          tes.start();
        }
        catch (IOException ex) {
        }
      }
    }
    catch (IOException ex) {
      System.err.println(ex);
    }

  }
  
  public ThreadedEchoServer(Socket s) {
    theConnection = s;
  }
  
  public void run() {
    try {
      OutputStream os = theConnection.getOutputStream();
      InputStream is = theConnection.getInputStream();
      while (true) {
        int n = is.read();
        if (n == -1) break;
        os.write(n);
        os.flush();
      }
    }
    catch (IOException ex) {
    }
    
  }
  
}

Note that explicit yields are not required because all the different threads will tend to block on calls to read() and accept().


Previous | Next | Top | Cafe au Lait

Copyright 1997, 1999 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified January 14, 1999