Remote Method Invocation(RMI) facilitates object function calls between Java Virtual Machines(JVMs)
Step 1
$ first we create interface program like
/*interface:inte.java*/
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface inte extends Remote
{
int add(int a,int b)throws RemoteException;
int sub(int a,int b)throws RemoteException;
int mul(int a,int b)throws RemoteException;
int div(int a,int b)throws RemoteException;
}
$ Save the program as inte.java, and compile the program
Step 2
$ Next create a server program like
/*Server Program:cserver.java*/
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
public class cserver extends UnicastRemoteObject implements inte
{
public cserver()throws RemoteException
{
super();
}
public int add(int a,int b)throws RemoteException
{
return a+b;
}
public int sub(int a,int b)throws RemoteException
{
return a-b;
}
public int mul(int a,int b)throws RemoteException
{
return a*b;
}
public int div(int a,int b)throws RemoteException
{
return a/b;
}
public static void main(String args[])
{
try
{
inte c1=new cserver();
String I="CI";
Naming.rebind(I,c1);
System.out.println("Server bound and started");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
$ Save the program as cserver.java, and compile the program
Step 3
$ Now create a client program like
/*Client Program:cclient.java*/
import java.rmi.*;
public class cclient
{
public static void main(String args[])
{
try
{
String I="CI";
inte c=(inte)Naming.lookup(I);
System.out.println("Ready to continue");
int i=c.add(2,3);
int j=c.sub(3,2);
int k=c.mul(2,4);
int l=c.div(4,2);
System.out.println(i);
System.out.println(j);
System.out.println(k);
System.out.println(l);
}
catch(Exception e)
{}
}
}
$ save the program as cclient.java, and compile like
Step 4
C:\java\jdk1.5.0\bin>javac inte.java
C:\java\jdk1.5.0\bin>javac cserver.java
C:\java\jdk1.5.0\bin>javac cclient.java
C:\java\jdk1.5.0\bin>rmic cserver
C:\java\jdk1.5.0\bin>start rmiregistry
// we see the new empty block cmd prompt
//new window
C:\java\jdk1.5.0\bin>java cserver
Server bound and started.
//new window
C:\java\jdk1.5.0\bin>java cclient
Ready to continue
5
1
8
2
0 Comments