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 service
import 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
That is a good tutorial
ReplyDeletehttp://extreme-java.blogspot.com
Who still uses RMI today? Or even stuff like CORBA, except maybe in legacy software;
ReplyDeleteNice tutorial, but except for students I don't see what use do you make of RMI today!
@Sandeep : Thank you... :-)
ReplyDelete@Sam: Yes agree with you... This is solely for the purpose of study... :-)
What technology to use to communicate between 2 JVMs if RMI is not the one?
ReplyDelete@myTechInfo: If you communicate between two JVM I think RMI is a good option since interoperability won't be an issue... But communication between two frameworks like .NET , java you can probably go for web services... Plus web services provide ease of programming, flexibility, modularity and interoperability...
ReplyDelete