Making the Remote Service
Step one: Make a Remote interface
Step two: Make a Remote Implementation
Step three: Generate Stubs
Step four: run rmiregistry
Step five: Start the service
Server Code
Remote interface
import java.rmi.*;
public interface MyRemoteInterface extends Remote{ //step 1.1
public int doCalc(int a,int b) throws RemoteException; //step 1.2 & step 1.3
}
Remote serviceimport java.net.MalformedURLException;
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class MyRemoteImplementation extends UnicastRemoteObject implements MyRemoteInterface {//step 2.1 & 2.2
public MyRemoteImplementation() throws RemoteException {} //step 2.3
public int doCalc(int a,int b){
int result=a+b;
System.out.println("Returned the result= "+result+" to client!");
return result;
}
public static void main(String args[]){
MyRemoteInterface service=null;
try {
service = new MyRemoteImplementation();
} catch (RemoteException e) {
e.printStackTrace();
}
try {
Naming.rebind("welcome", service); //step 2.4 and be sure to give a name without spaces
} catch (RemoteException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
Note: Server should have following three classes to work.How client works?
Note: Client should have following three classes to work.
Client does a lookup on the RMI registry and RMI registry returns the stub object. Stub pretends to be the real service and let client invokes the method in it.
Client Code
import java.rmi.*;
public class MyRemoteClient {
public static void main(String args[]){
new MyRemoteClient().getResult();
}
public void getResult(){
try{
MyRemoteInterface service=(MyRemoteInterface)Naming.lookup("rmi://127.0.0.1/welcome");//Client does
//the lookup on the RMI registry
int result=service.doCalc(1,2);
System.out.println("hello I got the result "+result);
}catch(Exception e){
e.printStackTrace();
}
}
}
Output

