Steps in creating a java RMI application

  1. Write the server interface. This should extend Remote. Each member function should throw a RemoteException.
    /* MathSrvrInterface.java */
    import java.rmi.*;
    
    public interface MathSrvrInterface extends Remote {
      public int square(int n) throws RemoteException;
    }
    

  2. Write the class that will reside on the server. The class must extend UnicastRemoteObject and implement the interface.

    /* MathSrvr.java */
    import java.rmi.*;
    import java.rmi.server.*;
    
    public class MathSrvr extends UnicastRemoteObject implements MathSrvrInterface {
    
      public MathSrvr () throws RemoteException {
      }
      public int square(int n) throws RemoteException {
        return n * n;
      }
    }
    

  3. Write a server which will register the class with the rmiregistry.
    /* MathSrvrServer.java */
    import java.rmi.Naming;
    
    public class MathSrvrServer
    {
    public static void main (String[] argv) {
        try {
          Naming.rebind ("MathSrvr", new MathSrvr ());
          System.out.println ("MathSrvr Server is ready.");
        } catch (Exception e) {
          System.out.println ("MathSrvr Server failed: " + e);
        }
      }
    }
    

  4. Write a client. This looks up the name of the server, creating a local instance of the interface. it can then call the member functions. Note that it has to know the name of machine on which the service is running.


    /* MathSrvrClient.java */
    import java.rmi.Naming;
    public class MathSrvrClient {
      public static void main (String[] argv) {
        try {
          MathSrvrInterface mathsrvr = 
            (MathSrvrInterface) Naming.lookup 
                 ("//127.0.0.1/MathSrvr");
          System.out.println 
             ("the square of 17 is " + mathsrvr.square(17));
        } catch (Exception e) {
          System.out.println ("MathSrvrClient exception: " + e);
        }
      }
    }
    

  5. Compile the four programs with javac.

  6. Create the stub programs.
    rmic MathSrvr

  7. Start up the rmiregistry with the command
    rmiregistry

  8. Start the Server program
    java MathSrvrServer

  9. Run the client
    java MathSrvrClient