Asynchronous TCP/IP client.

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


// Usage:  java Client2 [updateInrevalInSeconds]
class Client2 extends Thread {  
  final static String SVR_ADDRESS = "localhost";
  final static int    REQ_PORT = 2050;
  final static int    RES_PORT = 2051;

  Client2(int interval) {
    try {
      Writer out = new OutputStreamWriter(
                            new Socket(SVR_ADDRESS, REQ_PORT).getOutputStream());
      start();
      out.write(interval);
      out.flush();
    }catch(Exception e) { e.printStackTrace(); }
  }

  public void run() {
    try {
      final ObjectInputStream in = new ObjectInputStream(
                                     new Socket(SVR_ADDRESS, RES_PORT).getInputStream());
      while (true) {
        System.out.println((Date)in.readObject());
      }
    }catch(Exception e) { e.printStackTrace(); }
  }

  static public void main(String[] args) {
    new Client2(args.length > 0 ? Integer.parseInt(args[0]) : 10);
  }
}

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].