A Client for the Arith Server

This is quite simple:
Naming.lookup() returns a reference to the remote object which can be used in the usual way to invoke its methods (its methods which have been declared remote).
This is done within the   try{ }   construct. Once the reference is obtained, the client remotely invokes the method add() on given arrays.

Note that except for the call to lookup() the fact that the method add() is running on another computer is invisible.

Note also that to compile this code, the Math interface must be available to the client.


package mahmoud.ch8;
import java.rmi.*;
import java.net.*;
/**
 * @(#) ArithApp.java
 * @author Qusay H. Mahmoud
 */
public class ArithApp {
  
    public static void main(String argv[]) {
        int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 9};
        int b[] = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2};
        int result[] = new int[10];
        try {
           // replace hostname by the machine the server is running on
           Arith obj = (Arith)Naming.lookup("//Gateway/ArithServer");
           result = obj.add(a, b);
        } catch (Exception e) {
           System.out.println("ArithApp exception:"+e.getMessage());
           e.printStackTrace();
        }
        System.out.println("The sum of the arrays is: ");
        for (int j=0; j<10; j++) {
           System.out.print(result[j]+"    ");
        }
        System.out.println();
    }
}


Point to note - the stub.

Things are not quite what they appear to be. The reference, obj, is not actually the reference to the remote object itself, but to its stub, which has been downloaded from the server.

The stub (in this case, ArithImp_Stub.class) is a proxy for the actual remote object (in this case, ArithImp.class).

Mostly, you don't notice that you are not dealing directly with the 'real' (remote) object. But sometimes the difference can cause complications. For example, the client may want to invoke a method of a subclass of a remote class. If this subclass does not have its own remote interface, its methods will not appear in the stub of its parent. When the client tries to invoke these methods they are missing in the stub. Only the parent's remote methods are there.