Remote Method Invocation(RMI) Concept …..
Remote Method Invocation (RMI) is an API which allows an object to invoke away on an object that exists in another address space, which might be on an equivalent machine or on a foreign machine. Through RMI, object running during a JVM present on a computer (Client-side) can invoke methods on an object present in another JVM (Server-side). RMI creates a public remote server object that permits the client and server-side communications through simple method calls on the server object.
RMI
The communication between client and server is handled by using two intermediate objects: Stub object (on client side) and Skeleton object (on server-side).
Stub
The stub object on the client machine builds an information block and sends this information to the server. The block consists of
- An identifier of the remote object to be used
- Method name which is to be invoked
- Parameters to the remote JVM
Skeleton
The skeleton object passes the request from the stub object to the remote object. It performs the following tasks
- It calls the specified method on the important object present on the server.
- It forwards the parameters received from the stub object to the tactic.
A RMI Java Example
Create remote interface
package com.thasneem.rmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Calculator extends Remote {
public int add(int x, int y) throws RemoteException;
public int subtract(int x, int y) throws RemoteException;
public int multiply(int x, int y) throws RemoteException;
public int divide(int x, int y) throws RemoteException;
}
Implementation of the Remote Interface.
package com.thasneem.rmi;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class CalculatorRemote extends UnicastRemoteObject implements Calculator {
CalculatorRemote() throws RemoteException {
super();
}
public int add(int x,int y){
return x+y;
}
public int subtract(int x,int y){
return x-y;
}
public int multiply(int x,int y){
return x*y;
}
public int divide(int x,int y){
return x/y;
}
}
Create the Server
package com.thasneem.rmi;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class RmiApplication {
public static void main(String args[]){
try{
Calculator stub=new CalculatorRemote();
Registry rgsty = LocateRegistry.createRegistry(3000);
rgsty.rebind("calculate", stub);
}catch(Exception e){System.out.println(e);}
}
}
Create the client
package com.thasneem.rmi;
import java.rmi.Naming;
public class Client {
public static void main(String args[]){
try{
Calculator stub=(Calculator) Naming.lookup("rmi://localhost:3000/calculate");
System.out.println(stub.add(25,48));
System.out.println(stub.subtract(55,33));
System.out.println(stub.multiply(25,34));
System.out.println(stub.divide(65,5));
}catch(Exception e){}
}
}
Output
Thank You! …..