Java2all.com  

RMI Program in java





Share This Topic -

RMI Program Code and Example:

CLICK HERE for step by step learning with description of each step

To run program of RMI in java is quite difficult, Here I am going to give you four different programs in RMI to add two integer numbers.

First program is for declare a method in an interface.

Second Program is for implementing this method and logic.

Third program is for server side.

And last one is for client side.

At the last I will give steps to run this program in one system.

Calculator.java

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

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

CalculatorImpl.java
 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;
	}
}

CalculatorServer.java
 import java.rmi.Naming;

public class CalculatorServer 
{
	CalculatorServer()
	{
		try 
		{
			Calculator c = new CalculatorImpl();
			Naming.rebind("rmi://127.0.0.1:1099/CalculatorService", c);
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	public static void main(String[] args) 
	{
		new CalculatorServer();
	}
}

CalculatorClient.java
 import java.rmi.Naming;

public class CalculatorClient 
{
	public static void main(String[] args) 
	{
		try 
		{
			Calculator c = (Calculator) Naming.lookup("//127.0.0.1:1099/CalculatorService");
			System.out.println("addition : "+c.add(10, 15));
		} 
		catch (Exception e) 
		{
			System.out.println(e);
		}
	}
}

 
Steps to run this programs:
 
First of all put these four programs inside bin folder of JDK.
 
As an example suppose our JDK folder is inside java folder in drive D:
 
Now open command prompt and do following steps.
 
cd\
 
d:
 
cd Java\jdk1.6.0_23\bin
 
javac Calculator.java
 
javac CalculatorImpl.java
 
javac CalculatorServer.java
 
javac CalculatorClient.java
 
rmic CalculatorImpl
 
start rmiregistry
 
java CalculatorServer
 
open another cmd and again go to same path d:\Java\jdk1.6.0_23\bin
 
java CalculatorClient

Output:

Java2All.Com

 

Java2All.Com

 

Java2All.Com