RMI basic program-Add 2 numbers

1. Create Calculator.java file.Write following code in it.

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Calculator extends Remote
{
public long add(long a,long b)throws RemoteException;
}

 2. Create CalculatorImpl.java file.Write following code in it.

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class CalculatorImpl extends UnicastRemoteObject implements Calculator
{
protected CalculatorImpl() throws RemoteException
{
super();
}
public long add(long a,long b) throws RemoteException
{
return a+b;
}
}

 3. Create CalculatorServer.java file.Write following code in it.

import java.rmi.Naming;
public class CalculatorServer
{
CalculatorServer()
{
try
{
Calculator c = new CalculatorImpl();
Naming.rebind(“rmi://172.16.116.124/CalculatorService”,c); //write your ip address here
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new CalculatorServer();
}
}

4. Create CalculatorClient.java file.Write following code in it.

import java.rmi.Naming;
public class CalculatorClient
{
public static void main(String[] args)
{
try
{
Calculator c=(Calculator)Naming.lookup(“//172.16.116.124/CalculatorService”); //write your ip address here
 
System.out.println(“addition:”+c.add(10,15));
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Compiling the program:
1. Open command prompt.Goto directory where your files are stored and type following commands
2. Now open a new cmd window and goto same path where your files are stored and type following commands
You will get ouput i.e., addition:25
To know your ipaddress–> open cmd—> type “ipconfig”(without double quotes),you will find IPV4 address
 

Leave a Reply