next up previous contents
Next: RpcDispatcher Up: MessageDispatcher Previous: MessageDispatcher   Contents

Example

This section describes an example of how to use a MessageDispatcher.

  public class MessageDispatcherTest implements RequestHandler {
      Channel            channel;
      MessageDispatcher  disp;
      RspList            rsp_list;
      String             props; // to be set by application programmer

      public void start() throws Exception {
          channel=new JChannel(props);
          disp=new MessageDispatcher(channel, null, null, this);
          channel.connect("MessageDispatcherTestGroup");

          for(int i=0; i < 10; i++) {
              Util.sleep(100);
              System.out.println("Casting message #" + i);
              rsp_list=disp.castMessage(null,
                                        new Message(null, null, new String("Number #" + i)),
                                        GroupRequest.GET_ALL, 0);
              System.out.println("Responses:\n" +rsp_list);
          }
          channel.close();
          disp.stop();
      }

      public Object handle(Message msg) {
          System.out.println("handle(): " + msg);
          return new String("Success !");
      }

      public static void main(String[] args) {
          try {
              new MessageDispatcherTest().start();
          }
          catch(Exception e) {
              System.err.println(e);
          }
      }
  }

The example starts with the creation of a channel. Next, an instance of MessageDispatcher is created on top of the channel. Then the channel is connected. The MessageDispatcher will from now on send requests, receive matching responses (client role) and receive requests and send responses (server role).

We then send 10 messages to the group and wait for all responses. The timeout argument is 0, which causes the call to block until all responses have been received.

The handle() method simply prints out a message and returns a string.

Finally both the MessageDispatcher and channel are closed.



Bela Ban 2002-11-16