Quick Notes on Java RMI (Remote Method Invocation)

by Amit


What is RMI?

Source

Java Remote Method Invocation (Java RMI) enables the programmer to create distributed Java technology-based to Java technology-based applications, in which the methods of remote Java objects can be invoked from other Java virtual machines, possibly on different hosts. RMI uses object serialization to marshal and unmarshal parameters and does not truncate types, supporting true object-oriented polymorphism.

How does RMI work?

Say, we have a “Client” and a remote program “Server” and “Client” wants to invoke (remotely) a method defined by the “Server” on the remote Host. The communication between the two programs can be roughly represented by the following figure:


------- 1 ---4--- 2 -------
| CLIENT| ----> | STUB | ----> |SERVER|
------- -------- -------
3 |
<---------------------------------------

1. When the client calls a remote method, the call first invokes a Stub, which in RMI terminology is a Java object residing on the client machine. Its function is to present the same interfaces as the remote server. The stub works with other parts of the RMI system to formulate a request that is sent to the remote machine.

2. The stub forwards the request for remote method invocation to the server via the network communication link (2)

3. Server returns the results of the method invocation to the Client via the Stub (4)

Reference : Java 2 : The complete Reference, Herbert Schildt , TMH

The “Hello World” of RMI

This section uses examples from here . Visit this link to download the source codes.

The following “Hello World” RMI application uses a simple Client to a make a remote method invocation to a Server program and recieves a “hello World” message from the remote server.

The files needed for this tutorial are:

  1. Hello.java – a remote interface
  2. Server.java – a remote object implementation that implements the remote interface
  3. Client.java – a simple client that invokes a method of the remote interface

Next Steps:

A. Compile the files


amit@etch-desktop:~/jdk1.6.0_02/bin$ mkdir rmi-demo
amit@etch-desktop:~/jdk1.6.0_02/bin$ ./javac -d rmi-demo/ Hello.java Client.java
Server.java

B. Start the Java RMI registry, server, and client

i) Start the RMI registry (Linux, Solaris)


amit@etch-desktop:~/jdk1.6.0_02/bin$ rmiregistry &
[1] 6441

ii) Start the server (Linux, Solaris)

    etch-desktop:/home/amit/jdk1.6.0_02/bin# ./java -classpath rmi-demo/ -    
Djava.rmi.server.codebase=file:rmi-demo/ example.hello.Server &

iii) Start the Client (Linux, Solaris)


etch-desktop:/home/amit/jdk1.6.0_02/bin# ./java -classpath rmi-demo/ example.hello.Client

The output from the client is the following message:


response: Hello, world!

Links:
1. Java 6 Tech docs

Advertisements