Multi-Threaded Example
Home ] Up ] The ServerSocket Class ] Server Example ] Using a telnet Client ] Server Example ] [ Multi-Threaded Example ]

 

 

You'll note that the previous ReverseServer isn't very friendly. 

Here are some of its problems:

  • It accepts a single connection only
  • When the connection ends, it simply exits

Not terribly useful!

How can we do better? Use threads! Here's an example:

package networking;

import java.net.ServerSocket;
import java.net.Socket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *   Application to act as a Reverse server for multiple clients.
 *   An application can connect to this server on the specified port
 *   and send it text.  The server will reverse the text and send it back.
 *
 *   @author Bryan J. Higgs, 10 October 1999
 */
public class MultiReverseServer
{
  /**
   *   Main entry point.
   *   @param args the command line arguments
   *               args[0] contains port to use
   */
  public static void main(String[] args)
  {
    int port = -1;
    try
    {
      port = Integer.parseInt(args[0]);
    }
    catch (NumberFormatException e)
    {
      System.err.println("Invalid port number: " +
          args[0]);
      return;
    }
    
    ServerSocket socket = null;
    Socket incoming = null;
    int client = 0;
    try
    {
      socket = new ServerSocket(port);
      while (true)
      {
        // Wait on server socket for connection request
        incoming = socket.accept();
        // Create a handler thread for this request, and start it.
        new ReverseHandler(incoming, ++client).start();
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    finally
    {
      // Close the ServerSocket, regardless of success
      try
      {
        if (socket != null)
          socket.close();
      }
      catch (IOException e)
      {
        // Ignore any errors here
      }
    }
  }
}

/**
 *   Class to handle the connection request for a single client.
 */
class ReverseHandler extends Thread
{
  public ReverseHandler(Socket incoming, int client)
  {
    m_incoming = incoming;
    m_client = client;
    setName("ReverseHandler for client #" + m_client);
  }
  
  public void run()
  {
    BufferedReader in = null;
    PrintWriter out = null;
    
    try
    {
      // Get the connection input stream
      in = new BufferedReader(
              new InputStreamReader(
                  m_incoming.getInputStream() ) );
      // Get the connection output stream
      out = new PrintWriter(
                  m_incoming.getOutputStream(),
                  true        // autoflush
                );
      
      // Output greeting to client
      out.println(
          "Welcome to the Reverse Server!" +
          " You are client #" + m_client + "." +
          " Enter an empty line to exit.");
      
      // Loop, reversing each line received.
      while (true)
      {
        String line = in.readLine();
        if (line == null || line.equals(""))
          break;
        StringBuffer buffer = new StringBuffer(line);
        line = buffer.reverse().toString();
        out.println(line);
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    finally
    {
      // Close everything necessary
      try
      {
        if (out != null)
          out.close();
        if (in != null)
          in.close();
        if (m_incoming != null)
          m_incoming.close();
      }
      catch (IOException e)
      {
        // Ignore any errors here
      }
    }
  }
  
  //// Private data ////
  private Socket m_incoming;
  private int    m_client;
}

We simply use threads to handle multiple simultaneous connections.  The server looks exactly the same to its clients, except that it no longer goes away after the first connection ends.

 
The page was last updated February 19, 2008