Java Rmi Tutorial
Java Rmi Tutorial
Java RMI
Audience
This tutorial has been prepared for beginners to make them understand the basics of
Remote Method Invocation in Java.
Prerequisites
For this tutorial, it is assumed that the readers have a prior knowledge of Java
programming language. In some of the programs of this tutorial, we have used JavaFX for
GUI purpose. So, it is recommended that you go through our JavaFX tutorial before
proceeding further. http://www.tutorialspoint.com/javafx/
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at [email protected]
i
Java RMI
Table of Contents
About the Tutorial ..................................................................................................................................... i
Audience .................................................................................................................................................... i
Prerequisites .............................................................................................................................................. i
ii
Java RMI
iii
Java RMI ─ Introduction Java RMI
RMI stands for Remote Method Invocation. It is a mechanism that allows an object
residing in one system (JVM) to access/invoke an object running on another JVM.
Inside the server program, a remote object is created and reference of that object
is made available for the client (using the registry).
The client program requests the remote objects on the server and tries to invoke
its methods.
1
Java RMI
Transport Layer ─ This layer connects the client and the server. It manages the
existing connection and also sets up new connections.
Skeleton ─ This is the object which resides on the server side. stub communicates
with this skeleton to pass request to the remote object.
RRL (Remote Reference Layer) ─ It is the layer which manages the references
made by the client to the remote object.
When the client makes a call to the remote object, it is received by the stub which
eventually passes this request to the RRL.
When the client-side RRL receives the request, it invokes a method called invoke()
of the object remoteRef. It passes the request to the RRL on the server side.
The RRL on the server side passes the request to the Skeleton (proxy on the server)
which finally invokes the required object on the server.
At the server side, the packed parameters are unbundled and then the required method
is invoked. This process is known as unmarshalling.
2
Java RMI
RMI Registry
RMIregistry is a namespace on which all server objects are placed. Each time the server
creates an object, it registers this object with the RMIregistry (using bind() or reBind()
methods). These are registered using a unique name known as bind name.
To invoke a remote object, the client needs a reference of that object. At that time, the
client fetches the object from the registry using its bind name (using lookup() method).
Goals of RMI
Following are the goals of RMI:
3
Java RMI ─ RMI Application Java RMI
To write an RMI Java application, you would have to follow the steps given below:
Create an interface that extends the predefined interface Remote which belongs
to the package.
Declare all the business methods that can be invoked by the client in this interface.
Since there is a chance of network issues during remote calls, an exception named
RemoteException may occur; throw it.
Following is an example of a remote interface. Here we have defined an interface with the
name Hello and it has a method called printMsg().
import java.rmi.Remote;
import java.rmi.RemoteException;
4
Java RMI
Create a class that extends the implementation class implemented in the previous
step. (or implement the remote interface)
Export the remote object using the method exportObject() of the class named
UnicastRemoteObject which belongs to the package java.rmi.server.
Get the RMI registry using the getRegistry() method of the LocateRegistry class
which belongs to the package java.rmi.registry.
Bind the remote object created to the registry using the bind() method of the class
named Registry. To this method, pass a string representing the bind name and
the object exported, as parameters.
5
Java RMI
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public Server() {}
public static void main(String args[]) {
try {
System.err.println("Server ready");
} catch (Exception e) {
6
Java RMI
Create a client class from where you want invoke the remote object.
Get the RMI registry using the getRegistry() method of the LocateRegistry class
which belongs to the package java.rmi.registry.
Fetch the object from the registry using the method lookup() of the class Registry
which belongs to the package java.rmi.registry. To this method you need to pass
a string value representing the bind name as a parameter. This will return you the
remote object down cast it.
The lookup() returns an object of type remote, down cast it to the type Hello.
Finally invoke the required method using the obtained remote object.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
private Client() {}
try {
7
Java RMI
} catch (Exception e) {
Or,
Open the folder where you have stored all the programs and compile all the Java files as
shown below.
Javac *.java
8
Java RMI
start rmiregistry
Java Server
9
Java RMI
java Client
Verification: As soon you start the client, you would see the following output in the
server.
10
Java RMI ─ GUI Application Java RMI
In the previous chapter, we created a sample RMI application. In this chapter, we will
explain how to create an RMI application where a client invokes a method which displays
a GUI window (JavaFX).
import java.rmi.Remote;
import java.rmi.RemoteException;
import javafx.animation.RotateTransition;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Box;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
11
Java RMI
import javafx.scene.text.Text;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
import javafx.util.Duration;
@Override
public void start(Stage stage) {
// Drawing a Box
Box box = new Box();
12
Java RMI
13
Java RMI
{
@Override
public void handle(KeyEvent event) {
// Playing the animation
rotateTransition.play();
}
};
// Adding an event handler to the text feld
textField.addEventHandler(KeyEvent.KEY_TYPED, eventHandlerTextField);
@Override
public void handle(javafx.scene.input.MouseEvent e) {
rotateTransition.stop();
}
};
// Adding the event handler to the box
box.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED,
eventHandlerBox);
// Setting camera
PerspectiveCamera camera = new PerspectiveCamera(false);
camera.setTranslateX(0);
camera.setTranslateY(0);
camera.setTranslateZ(0);
scene.setCamera(camera);
14
Java RMI
Server Program
An RMI server program should implement the remote interface or extend the
implementation class. Here, we should create a remote object and bind it to the
RMIregistry.
Following is the server program of this application. Here, we will extend the above created
class, create a remote object, and registered it to the RMI registry with the bind name
hello.
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public Server() {}
try {
// Instantiating the implementation class
FxSample obj = new FxSample();
15
Java RMI
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Client Program
Following is the client program of this application. Here, we are fetching the remote object
and invoking its method named animation().
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
try {
// Getting the registry
Registry registry = LocateRegistry.getRegistry(null);
16
Java RMI
Step 1: Open the folder where you have stored all the programs and compile all the Java
files as shown below.
Javac *.java
start rmiregistry
17
Java RMI
Java Server
java Client
18
Java RMI
Verification: As soon you start the client, you would see the following output in the
server.
19
Java RMI ─ Database Application Java RMI
In the previous chapter, we created a sample RMI application where a client invokes a
method which displays a GUI window (JavaFX).
In this chapter, we will take an example to see how a client program can retrieve the
records of a table in MySQL database residing on the server.
Assume we have a table named student_data in the database details as shown below.
+----+--------+--------+------------+---------------------+
| ID | NAME | BRANCH | PERCENTAGE | EMAIL |
+----+--------+--------+------------+---------------------+
| 1 | Ram | IT | 85 | [email protected] |
| 2 | Rahim | EEE | 95 | [email protected] |
| 3 | Robert | ECE | 90 | [email protected] |
+----+--------+--------+------------+---------------------+
Assume the name of the user is myuser and its password is password.
20
Java RMI
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.*;
21
Java RMI
Here we are implementing the getStudents() method of the Remote interface. When
you invoke this method, it retrieves the records of a table named student_data. Sets
these values to the Student class using its setter methods, adds it to a list object and
returns that list.
import java.sql.*;
import java.util.*;
// Database credentials
String USER = "myuser";
String PASS = "password";
// Open a connection
22
Java RMI
// Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
23
Java RMI
Server Program
An RMI server program should implement the remote interface or extend the
implementation class. Here, we should create a remote object and bind it to the
RMIregistry.
Following is the server program of this application. Here, we will extend the above created
class, create a remote object and register it to the RMI registry with the bind name hello.
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
try {
// Instantiating the implementation class
ImplExample obj = new ImplExample();
System.err.println("Server ready");
} catch (Exception e) {
24
Java RMI
Client Program
Following is the client program of this application. Here, we are fetching the remote object
and invoking the method named getStudents(). It retrieves the records of the table from
the list object and displays them.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.*;
private Client() {}
try {
// Getting the registry
Registry registry = LocateRegistry.getRegistry(null);
// System.out.println("bc "+s.getBranch());
25
Java RMI
Step 1: Open the folder where you have stored all the programs and compile all the Java
files as shown below.
Javac *.java
start rmiregistry
26
Java RMI
Java Server
java Client
27