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
- Interface program
- Implementation program
- Server program
- 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)
- import java.rmi.*;
- public interface rint extends Remote {
- double fact(double x) throws RemoteException;
- }
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)
- import java.rmi.*;
- import java.rmi.server.*;
- public class rimp extends UnicastRemoteObject implements rint {
- public rimp() throws RemoteException {}
- public double fact(double x) throws RemoteException {
- if (x <= 1) return (1);
- else return (x * fact(x - 1));
- }
- }
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)
- import java.rmi.*;
- import java.net.*;
- public class rser {
- public static void main(String arg[]) {
- try {
- rimp ri = new rimp();
- Naming.rebind("rser", ri);
- } catch (Exception e) {
- System.out.println(e);
- }
- }
- }
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)
- import java.rmi.*;
- public class rcli {
- public static void main(String arg[]) {
- try {
- rint rr = (rint) Naming.lookup("rmi://172.16.13.2/rser");
- double s = rr.fact(5);
- System.out.println("Factorial value is… : " + s);
- } catch (Exception e) {
- System.out.println(e);
- }
- }
- }
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 2
Step 3
Step 4
Step 5
Step 6
Summary
In the above blog, the remote method invocation concept has been implemented successfully.