back    home


Multithreaded Server Example

The example in its current state works between the server program and one client program only. To allow multiple client connections, the server program has to be converted to a multithreaded server program. The threaded version implements the Runnable interface. This interface has one method, run, which provides a prototype for programs that want to execute code while they are active.

class SocketThrdServer extends JFrame
                implements ActionListener,
                Runnable { ... }

The listenSocket method loops on the server.accept call waiting for client connections and starts a Thread when it receives a client connection.

    while(true){
      try{
        client = server.accept();
        Thread t = new Thread(frame);
        t.start();
      } catch (IOException e) {
        System.out.println("Accept failed: 4321");
        System.exit(-1);
      }
    }


The run method executes independently in each thread that is started. If three clients request connections, three threads are started, and three run methods execute the following code for their respective threads. The run method creates the input buffer and output writer, loops on the input stream waiting for input from the client, and sends the data it receives back to the client.

  public void run(){
      BufferedReader in = null;
      PrintWriter out = null;
    try{
      in = new BufferedReader(new InputStreamReader(
		client.getInputStream()));
      out = new PrintWriter(client.getOutputStream(), true);
    } catch (IOException e) {
      System.out.println("in or out failed");
      System.exit(-1);
    }

    while(true){
      try{
        line = in.readLine();
//Send data back to client
       out.println(line);
       } catch (IOException e) {
         System.out.println("Read failed");
         System.exit(-1);
       }
    }
  }


The finalize() method is called by the Java virtual machine (JVM)* before the program exits to give the program a chance to clean up and release resources. Multi-threaded programs should close all Files and Sockets they use before exiting so they do not face resource starvation. The call to server.close() in the finalize() method closes the Socket connection used by each thread in this program.

  protected void finalize(){
//Objects created in run method are finalized when
//program terminates and thread exits
     try{
        server.close();
    } catch (IOException e) {
        System.out.println("Could not close socket");
        System.exit(-1);
    }
  }


back   home