The following code example shows how to create a RequestServer that lets you telnet into a port, type your name, and have it printed back to you. First, you must define a subclass of RequestServerHandler:

import java.io.*;
import java.net.*;
import atg.server.tcp.*;
public class MirrorHandler
extends RequestServerHandler
{
  public MirrorHandler (ThreadGroup group,
                        String threadName,
                        RequestServer server,
                        Socket socket)
  {
    super (group, threadName, server, socket);
  }

  protected void handleRequest (Socket socket)
  {
    try {
      BufferedReader br = new BufferedReader(new
         InputStreamReader(socket.getInputStream()));
      OutputStream out = socket.getOutputStream ();
      PrintStream pout = new PrintStream (out);

      String name = br.readLine ();
      pout.println ("Hello " + name + "!");
    } catch (IOException exc) {}
    finally {
      try { if (socket != null) socket.close (); }
      catch (IOException exc) {}
  }
}

Ignore the constructor, since your constructor will probably always look like that. Look at the handleRequest method, which contains the code that reads a line and sends it back. Note the use of try...finally, which insures that no matter what happens inside the handler, the socket will always be closed. This is important because sockets are a limited resource, and leaving them open accidentally because of unanticipated errors can cause you eventually to run out of sockets.

Remember that these objects are reused from request to request. If you find that you are doing a lot of setup in each request, that setup might be hurting your throughput. See if you can move some of the setup to the constructor by creating objects that can be reused from request to request.

Also be aware that your handler need not be thread-safe. You can be assured that only one request will be running through your request handler at any one time. The RequestServer will spin off multiple handler objects to handle multiple simultaneous requests. This should help you make your handler more efficient for reuse.

In addition to extending RequestServerHandler, you must also extend RequestServer to tell it what subclass of RequestServerHandler to create:

import java.net.*;
import atg.server.tcp.*;
public class Mirror
extends RequestServer
{
  public Mirror ()
  {
    super ();
  }

  protected RequestServerHandler createHandler (ThreadGroup group,
                                                String threadName,
                                                Socket socket)
  {
    return new MirrorHandler (group, threadName, this, socket);
  }
}

That should be all you need to do for RequestServer.

 
loading table of contents...