Asynchronous TCP/IP server.

Architect's Corner
Servlet adapters can solve your socket problems
by Andrei Nazariev
Listing 3. Asynchronous TCP/IP server.


  class Server2 extends Thread {
  final static int    REQ_PORT = 2050;
  final static int    RES_PORT = 2051;
  private ObjectOutputStream responseOutput;

  Server2() {
    try {
      start();
      responseOutput = new ObjectOutputStream(
                         new ServerSocket(RES_PORT). accept().getOutputStream());
    }catch(IOException e) { e.printStackTrace(); }
  }

  public void run() {
    try {
      final InputStream in = new ServerSocket(REQ_PORT). accept().getInputStream();
      int interval = in.read();
      new Timer().schedule(task, 0, interval*1000);
    }catch(IOException e) {
      e.printStackTrace();
      System.exit(1);
    }
  }

  final private TimerTask task = new TimerTask() {
    public void run() {
      try {
        if (responseOutput != null) {
          responseOutput.writeObject(new Date());
          responseOutput.flush();
        }
      }catch(IOException e) {
        e.printStackTrace();
        System.exit(2);
      }
    }
  };

  static public void main(String[] args) {
    new Server2();
  }
}

About the Author

Andrei Nazariev is a senior Java architect at Sun Microsystems' Sun Java Center in Orlando, FL. He can be contacted at [email protected].