
// RPCClient.java
// Andrew Davison, ad@coe.psu.ac.th, May 2023

/* A client/server example where the server executes RPCs
   sent by a client.

   Each RPC is represented by two tuples of the form:
      (callerID, "func", functionName);    
      (callerID, "args", <series of function arguments>);
   e.g.
      ("Alice1", "func", "add3")  
      ("Alice1", "args", 1, 2, 3)
   represents the function call: add3(1,2,3)

  The server replies with a single tuple of the form:
      (callerID, "result", ObjectResult)

  This client sends two RPCs: add3(1,2,3) and concat("a","b")
  and prints their results returned by the server.

  Explained in section 3.7 at:
    https://github.com/pSpaces/Programming-with-Spaces/blob/master/tutorial-distributed-programming.md

  Usage:
    > compile.bat RPCClient.java
    > run.bat RPCClient
       -- start in a new window after starting RPCServer

    Part of the application made up of:
       * RPCServer.java
       * RPCClient.java
*/


import org.jspace.*;


public class RPCClient
{
  private final static String REMOTE_URI = 
                  "tcp://127.0.0.1:9001/rpcSpace?keep";


  public static void main(String[] argv)
  {
    try {
      System.out.println("Connecting to RPC server at: " + REMOTE_URI);
      RemoteSpace space = new RemoteSpace(REMOTE_URI);

      System.out.println("\nPut add3(1,2,3) in space:");

      // represent the function call as *two* tuples
      space.put("Alice1", "func", "add3");    
               // Alice1 is a unique caller ID
      space.put("Alice1", "args", 1, 2, 3);

      Object[]response = space.get(new ActualField("Alice1"),
                            new ActualField("result"),
                            new FormalField(Integer.class));
      System.out.println("add3(1,2,3) = " + response[2]);


      System.out.println("\nPut concat(\"a\",\"b\") in space:");
      space.put("Alice2", "func", "concat");    // two tuples
      space.put("Alice2", "args", "a", "b");

      response = space.get(new ActualField("Alice2"),
                            new ActualField("result"),
                            new FormalField(String.class));
      System.out.println("concat(\"a\",\"b\") = " + response[2]);

      space.close();
    }
    catch (Exception e)  
    { System.out.println(e);  }
  } /* main */


}  // end of RPCClient class
