Remote Method Invocation(RMI) Concept
RMI is the object oriented equivalent of RPC (Remote Procedure Call). It called as remote method invocation. Remote method invocation (RMI) allow a java object to invoke method on an object running on another machine. RMI provide remote communication between java program.
Concept of RMI application
A RMI application can be divided into two part. One is Client program and another Server program. A Server program creates some remote object, make their references available for the client to invoke method on it. A Client program make a request for remote objects on server and invoke method on them. Stub and Skeleton are two important objects used for communication with remote object.
Stub and skeleton
Stub and Skeleton are two important objects used for communication with remote object.
Stub —
Stub, which is an object use in RMI as a gateway for the client side. All the outgoing requests are going through it. When a client invokes a method,
1. A connection is established using remote virtual machine.
2. It the transmit parameters for remote virtual machine. This is call as marshals.
3. Then wait for output
4. It reads the return value or exception. This call as unmarshals.
5. Final step is return values to caller , are performed.
Skeleton —
Skeleton, which is an object use in RMI as a gateway for the server side. All the incoming requests are coming through it. When a server invokes a method,
- Reads the parameter for the remote method
- Invokes the method on the actual remote object.
- Writes and transmits (marshals) the result to the caller.
For example,
Requirement — Create a web service to find whether given number is prime or not using java RMI.
The remote interface
A remote interface provides the description of all the methods of a particular remote object. The client communicates with this remote interface. The Remote Interface that both Server and Client will implement. This always be public and extend Remote. All methods described in the Remote interface must list RemoteException in their throws clause. (In the example here, used seperated client side and server side projects. For that Clent side and Server side should have remote Interfaces with same name.)
Here has only one method. it receives a int parameter and returns Boolean.
Implementation of remote Interface
Server
This is done using rebind() method of java.rmi.Naming class. rebind() method take two arguments, first represent the name of the object reference and second argument is reference to instance.
Client Application
This file containe java program that invoke lookup() method of the naming class.
Let’s execute this.
This creates the stub asPrimeNumberImplementation_Stub.class(according to PrimeNumberImplementation.java).
As server side result we get,
As clentside result we get,
Thank you…!