Thursday, October 25, 2012

Java RMI

The Java Remote Method Invocation (RMI) system allows an object running in one Java virtual machine to invoke methods on an object running in another Java virtual machine. RMI provides for remote communication between programs written in the Java programming language.
That is the definition of RMI provided by Oracle on this page. So, now let's have fun with RMI.

We will create two classes that act as a client and a server. The client consumes object provided by server. First we create the object which is a POJO that implements Remote and Serializable. All the methods that are accessible from client (which are public methods) should declare RemoteException.



Next we create the client. It does the following things in order: Locate remote server host which in my case is localhost, lookup User object, and then update user's address. A note here is that the update is not persisted to the object on server, it is kept locally.



Now we will take a look at the server class. The server first will create a registry at port 1099. It then creates a User object and bind it to the "user" registry. After that, it will execute infinite loop while waiting for user's interaction.

If user types 'a', the User's address is updated and the update is available for the next clients looking up for it when they call lookup() method.

If user types 'b', the User object is unbound so that an error is thrown if next clients looking up for it.

If user types 'c', the "user" registry is replaced with new object user2; this is known as rebind.

If user press 'p', it will simply write user's properties to console.



0 comments:

 

©2009 Stay the Same | by TNB