RMI is the object-oriented version of Remote Procedure Calls. – it is a mechanism use to invoke methods of objects that reside in
RMI is carried out by two objects, stub and skeleton. This is explained below:
A stub is an object that is present at the client side and represents the functionality of the remote object. The stub receives the parameters from the client-side and is responsible for getting the return values from the server. All requests from the client to the server are routed through the stub.
Just as the stub acts as a middleman at the client-side, the skeleton receives incoming requests at the server-side. It is responsible for passing the parameters and invoking the server’s service, getting the result from the server, and sending it back to the client.
The RMI Registry is kind of like a directory that acts as a liaison between the server and client. The server registers its services with the registry and the client can look these services up from there.
Step 1: Definition and implementation of the remote server
The interface should extend Remote
and all method definitions should throw RemoteException
. The implementation of the interface should extend UnicastRemoteObject
and it should have a constructor that throws RemoteException
.
For the sake of this example, let’s consider an interface Library
and its implementation AcademicLibrary
, which provides the getBooks()
method.
Step 2: Creation of stub and skeleton objects
Execute the following command on the command prompt:
rmic AcademicLibrary
Step 3: Initialization of the RMI Registry
Execute the following command on the command prompt:
start rmiregistry 5000
.
Here, 5000
specifies the port.
Step 4: Creation and execution of server and client applications
import java.rmi.*;import java.rmi.registry.*;public class LibraryServer{public static void main(String args[]){try{// An object of the remote interface implementationLibrary library = new AcademicLibrary();// Binding the remote object to the name libraryNaming.rebind("rmi://localhost:5000/library",library);}catch(Exception exception){System.out.println(exception);}}}
import java.rmi.*;public class LibraryClient{public static void main(String args[]){try{//Finding reference of the remote objectLibrary library = (Library)Naming.lookup("rmi://localhost:5000/library");String[] books = library.getBooks();for (String book : books)System.out.println(book);}catch(Exception exception){System.out.println(exception);}}}