Advanced Java Programming - Old Questions

3. What is RMI? How can you use RMI to develop a program that runs in different machine? Discuss with suitable example.

10 marks | Asked in 2070

RMI is a mechanism that allows an object running in one java virtual machine (JVM) to invoke methods on an object running in another java virtual machine (JVM). RMI provides remote communication between java programs. Objects with methods that can be invoked across JVMs are called remote objects. The remote object is called the server object.

To create an application that uses RMI, one needs to use the classes and interfaces defined by the java.rmi package.
To create an RMI application, the following steps need to be followed:

1. Define a remote interface

2. Implement the remote interface

3. Develop the server application program

4. Develop a client application program

5. Generate Stubs and Skeletons

6. Start the RMI registry on server machine

7. Start the server

8. Start the client

Example:

Define a remote interface

import java.rmi.*;

public interface Adder extends Remote

{

      public int add(int a,int b)throws RemoteException;

}

Implementation of remote interface

import java.rmi.*;

import java.rmi.server.*;

public class AdderRemote extends UnicastRemoteObject implements Adder

{

      AdderRemote()throws RemoteException{

      super();

}

public int add(int a,int b)

{

      return a+b;

}

}


Writing the Server Program

import java.rmi.*;

import java.rmi.registry.*;

public class AddServer {

  public static void main(String args[]) {

      try {

            AdderRemote s1=new AdderRemote();

            LocateRegistry.createRegistry(1099);

            Naming.rebind("AddService",s1);

           }

      catch(Exception e) {

            System.out.println(e);

      }

  }

}


Writing the Client Program

import java.rmi.*;

public class Client {

   public static void main(String args[]) {

      try{

            String ip="rmi://127.0.0.1/Addservice";

            Adder st = (Adder)Naming.lookup(ip);

            System.out.println(st.sum(25,8));

      }

      catch(Exception e) {

            System.out.println(e);

      }

   }

}