Asynchronous HTTP client.

Architect's Corner
Servlet adapters can solve your socket problems
by Andrei Nazariev
Listing 6. Asynchronous HTTP client.


// Usage:  java RestrictedClient2 [updateInrevalInSeconds]
class RestrictedClient2 extends Thread {
  //this line has to be modified according to your particular Web
  //server
  final static String servletCodeBase = "http://localhost:8080/servlet/";

  RestrictedClient2(int interval) {
    try {
      start();
      URL url = new URL(servletCodeBase + RequestAdapter?
interval=" + interval);
      BufferedReader reader = new BufferedReader(
                                new InputStreamReader(url.open
Connection().getInputStream()));
      if (!reader.readLine().equals("Success")) {
        System.out.println(" Couldn't subscribe to server. Exiting!");
        System.exit(1);
      }
    }catch(Exception e) { e.printStackTrace(); }
  }

  public void run() {
    try {
      URL url = new URL(servletCodeBase + "ResponseAdapter");
      InputStream is = url.openConnection().getInputStream();
      ObjectInputStream in = new ObjectInputStream(is);
      while (true) {
        System.out.println((Date)in.readObject());
      }
    }catch(Exception e) { e.printStackTrace(); }
  }

  static public void main(String[] args) {
    new RestrictedClient2(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 nazariev@pobox.com.

Featured

Upcoming Events

AppTrends

Sign up for our newsletter.

I agree to this site's Privacy Policy.