Implementation Of Remote Method Invocation Concept In Java

Remote Method Invocation

 
RMI (Remote Method Invocation) is a way that a programmer, using the Java programming language and development environment, can write object-oriented programming in which objects on different computers can interact in a distributed network. 
 

Working with RMI

  1. Interface program
  2. Implementation program
  3. Server program
  4. Client program
Example: Calculating the factorial of a given number using the RMI concept.

 
Step 1: Interface Program

 
Declare the Methods only.
 
Open the first note pad, type the following program, and save the file as “rint.java”.
 
Interface Program (rint.java)
  1. import java.rmi.*;  
  2. public interface rint extends Remote {  
  3.  double fact(double x) throws RemoteException;  
  4.  

Step 2: Implementation Program

 
Define Methods only.
 
Open the second note pad, type the following program, and save the file as “rimp.java”.
 
Implementation Program (rimp.java)
  1. import java.rmi.*;  
  2. import java.rmi.server.*;  
  3. public class rimp extends UnicastRemoteObject implements rint {  
  4.  public rimp() throws RemoteException {}  
  5.  public double fact(double x) throws RemoteException {  
  6.   if (x <= 1return (1);  
  7.   else return (x * fact(x - 1));  
  8.  }  
  9. }  

Step 3: Server Program

 
It is the main program.
 
Open the third note pad, type the following program, and save the file as “rser.java”.
 
Server Program (rser.java)
  1. import java.rmi.*;  
  2. import java.net.*;  
  3. public class rser {  
  4.  public static void main(String arg[]) {  
  5.   try {  
  6.    rimp ri = new rimp();  
  7.    Naming.rebind("rser", ri);  
  8.   } catch (Exception e) {  
  9.    System.out.println(e);  
  10.   }  
  11.  }  
  12. }  

Step 4: Client Program

 
It is the data send (request) to the Server program.
 
Open the fourth note pad, type the following program, and save the file as “rcli.java”.
 
Client Program (rcli.java)
  1. import java.rmi.*;  
  2. public class rcli {  
  3.  public static void main(String arg[]) {  
  4.   try {  
  5.    rint rr = (rint) Naming.lookup("rmi://172.16.13.2/rser");  
  6.    double s = rr.fact(5);  
  7.    System.out.println("Factorial value is… : " + s);  
  8.   } catch (Exception e) {  
  9.    System.out.println(e);  
  10.   }  
  11.  }  
  12. }  
Explanation
 
Compile
and Execute the Program.
 
In a single system, let us assume that we can open two command prompts. One command prompt is called Server while the other one is called Client.
 
Step 1
 
Step
 
Step 2
 
Step
 
Step 3
 
Step
 
Step 4
 
Step
 
Step 5
 
Step
 
 Step 6
 
Step
 

Summary

 
 In the above blog, the remote method invocation concept has been implemented successfully.