6.java RMI
6.java RMI
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.
return id;
return name;
return branch;
return email;
this.id = id;
this.name = name;
this.branch = branch;
this.percent = percent;
this.email = email;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.*;
// Creating Remote interface for our application
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
Class.forName("com.mysql.jdbc.Driver");
//Open a connection
//Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
int id = rs.getInt("id");
student.setName(name);
student.setBranch(branch);
student.setPercent(percent);
student.setEmail(email);
list.add(student);
rs.close();
return list;
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 RMI registry.
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;
public Server() {}
try {
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
e.printStackTrace();
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 {
// System.out.println("bc "+s.getBranch());
// System.out.println(list);
} catch (Exception e) {
e.printStackTrace();