You are on page 1of 2

RMI CALCULATOR EXAMPLE

Interface
public interface Calculator extends java.rmi.Remote {

public void add(int num1, int num2)


throws java.rmi.RemoteException;

public void mul(int a, int b)


throws java.rmi.RemoteException;

public void sub(int num1, int num2)


throws java.rmi.RemoteException;
}

Implement Class
public class Cal extends java.rmi.server.UnicastRemoteObject implements
Calculator {

public Cal() throws java.rmi.RemoteException {


super();
}
public void add(int a, int b) throws java.rmi.RemoteException{
int sum=a+b;
System.out.println("Sum:"+sum);
}
public void mul(int a, int b) throws java.rmi.RemoteException{
int mul=a*b;
System.out.println("Mul:"+mul);

}
public void sub(int n, int m) throws java.rmi.RemoteException{
int sub=n-m;
System.out.println("Sub:"+sub);
}
}
Binding registry
import java.rmi.Naming;

public class Call {


public Call() {
try {
Cal c = new Cal();
Naming.rebind("rmi://localhost/Call", c);
}
catch (Exception e) {
System.out.println("Server Error: " + e);
}
}
public static void main(String args[]) {
//Create the new Calculator server
new Call();
}
}
CLIENT CLASS

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

public class Client {

public static void main(String[] args) throws NotBoundException,


MalformedURLException {
try {

Calculator c = (Calculator)
Naming.lookup("rmi://localhost/Call");
c.add(23,34);
c.mul(2, 3);
c.sub(23, 10);
// Catch the exceptions that may occur - rubbish URL, Remote
exception
} catch (RemoteException re) {
System.out.println("RemoteException"+re);
}
}
}

You might also like