A Quick Peek Into Java Remote Method Invocation(RMI)

SENG 41283 — Distributed and Cloud Computing

What is Java RMI?

Typical implementation model of Java-RMI using stub and skeleton objects

Remote Object

Stub

Skeleton

  1. First, let’s define the remote interface. This will be used by both client and server to refer the remote object.
// Calculator.javaimport java.rmi.*;public interface Calculator extends Remote
{
int add(int x,int y) throws RemoteException;
int subtract(int x,int y) throws RemoteException;
int multiply(int x,int y) throws RemoteException;
int divide(int x, int y) throws RemoteException;
}
// CalculatorImpl.javaimport java.rmi.*;
import java.rmi.server.*;
public class CalculatorImpl extends UnicastRemoteObject implements Calculator
{
public CalculatorImpl() 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)
{
if(y != 0)
{
return x / y;
}
else
{
return -1;
}
}
}
rmic CalculatorImpl
// Server.javaimport java.rmi.*;
import java.rmi.registry.*;
public class Server
{
public static void main(String[] args)
{
try
{
Calculator stub = new CalculatorImpl();
Naming.rebind("rmi://localhost:5000/calculate", stub);
} catch (Exception e)
{
System.out.println(e.toString());
}
}
}
// Client.javaimport java.rmi.*;public class Client
{
public static void main(String[] args)
{
int x = 15, y = 5;
try
{
Calculator stub = (Calculator) Naming.lookup("rmi://localhost:5000/calculate");

System.out.println("x = " + x + "| y = " + y);
System.out.println("x + y: " + stub.add(x, y));
System.out.println("x - y: " + stub.subtract(x, y));
System.out.println("x * y: " + stub.multiply(x, y));
System.out.println("x / y: " + stub.divide(x, y));
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
}
  1. Start the registry server using at port 5000 in the first shell,
rmiregistry 5000
java Server
java Client

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store