RMI (Remote Method Invocation) Communication Example

RMI allows you to set up an object so it runs on a remote host and then execute operations on that object just as if you were executing methods on non-RMI-based objects. For example, you could set up an object representing a time log with operations to add and retrieve data. The object would be stored in a file so you don't lose information every time the server is restarted.

You must create several pieces to use RMI in an application:

Once the application has been set up, you use it by doing the following:
  1. Compile the implementation.
  2. Run rmiregistry 10000 (using the same port number as in CounterServiceImpl.java)
  3. Run the server implementation.
  4. Run the client(s).
Note that you must run rmiregistry before you can start your server, and the server must be running before you can start any clients.

For example, consider the following Java files which implement a simple counter:

To run this application on server Xyz, do the following:

  1. Copy the files to your home directory.
  2. Edit CounterServiceImpl.java to update the service name, port id (see above for suggested formats), and service host.
  3. Compile all code with
            javac *.java
    
  4. Type
            rmiregistry port
    
    to start rmiregistry (where port is the number used in the second step).
  5. Log in to the host and type
            java CounterServiceImpl
    
    Note that neither rmiregistry nor CounterServiceImpl exits until you type Control-C.
  6. Do one of the following:

For More Information

The above information was gleaned from Both books contain further information such as how to make the server "call back" to the client to inform the client of changes to the data stored on the server.

More information is available at Sun's RMI documentation site. Please let me know of other sites you find that are useful.

Security

Warning: be careful about running rmiregistry; there could be any a number of ways it could be used by another user to gain access to your files. It would generally be better to quit rmiregistry when you're not using it to test. Also, you would definitely want to investigate the security issues before using this tool in industry!