- A Lightweight Java Middleware
<< Example 3b   Example 4b >>

Example 4a

shows how to run an Agent on a remote server THERE and make it talk back to a Listener HERE.

The example uses two connections, one from a proxy Agent HERE to a real Agent THERE and another one for the opposite direction, connecting a proxy Listener THERE with a real Listener HERE.

While essentially just a doubling of the technique shown before, the example points out that again all can be accomplished from the client side: a proxy Agent is used to install a real Agent on the remote server and this Agent is equipped with a proxy Listener complete with all communication machinery letting it talk to a real Listener in the local process.


How to do it

Sounds and looks complicated and indeed is complicated to a degree, but takes only a few lines of code:


package tw.net.ocs.example;

import tw.net.ocs.*;
import tw.net.ocs.proxy.*;

public class Example4a {

   public static void main(String[] args) {

      System.out.println("Running Example4a: Listener HERE, Agent THERE");

         // Step 1: Provide the connection from THERE to HERE

         // Create a server instance (to host the Listener
         // that the remote Agent will talk to)
      OCSServer serverHere=OCSServer.createInstance(
         23230,  // listen at this port
         "serverHere"  // named 'serverHere'
         // ... and start it

         // Create a proxy Listener to be passed to the remote Agent.
         // Since it should talk to a subject in the server HERE we equip
         // the proxy with an OCSClient configured to talk to 'serverHere':
      ListenerImpl listenerThere = new TwNetOcsExampleListenerImpl(
         OCSClient.createInstance(  // give it a new OCSClient
            serverHere,  // which connects with 'serverHere',
            null,  // is unnamed, 
            false  // and not made the standard instance
         true,  // tell the proxy Listener to create a new Listener instance 
         null  // with an arbitrary name

         // Step 2: Provide the connection from HERE to THERE

         // Create an OCSClient instance that
         "localhost",  // communicates with a server at this host
         23229,  // and this port,
         null,  // unnamed, and 
         true  // made the standard client to use by subsequently created proxies

         // Allocate a proxy Agent and pass it the proxy Listener created above.
         // (This will transfer the proxy Listener complete with its client 
         // to the remote Agent THERE, turning every call of the Listener THERE 
         // into a call of the Listener HERE.)
      Agent agent = new TwNetOcsExampleAgent(listenerThere);
         // ... and let the Agent act


To run the demo,
start a server in a separate shell:

java -cp ocs.jar tw.net.ocs.OCSServer -start -port 23229

and run Example4a:

java -cp ocs.jar;ocs-examples.jar tw.net.ocs.example.Example4a
Last modified Jun 8, 2006