[go: up one dir, main page]

0% found this document useful (0 votes)
8 views11 pages

Unit 3

The document provides a comprehensive overview of Remote Method Invocation (RMI) in Java, detailing its architecture, key components, and the process of developing RMI applications. It covers the roles of stubs and skeletons, marshalling and unmarshalling, and the use of RMI registries for object registration. Additionally, it discusses pushing data from RMI servlets and the interoperability of RMI with CORBA through RMI-IIOP.

Uploaded by

rjfdfn8rjd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views11 pages

Unit 3

The document provides a comprehensive overview of Remote Method Invocation (RMI) in Java, detailing its architecture, key components, and the process of developing RMI applications. It covers the roles of stubs and skeletons, marshalling and unmarshalling, and the use of RMI registries for object registration. Additionally, it discusses pushing data from RMI servlets and the interoperability of RMI with CORBA through RMI-IIOP.

Uploaded by

rjfdfn8rjd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

The New College (Autonomous), Chennai-14.

Department of Computer Applications – Shift - II


Study Material

Subject: Advanced Java Programming (20BHM407) Class: II BCA


---------------------------------------------------------------------------------------------------------------------------------------
UNIT-III: RMI
Overview – Developing applications with RMI: Declaring & Implementing remote interfaces-stubs & skeletons,
registering remote objects, writing RMI clients – Pushing data from RMI Servlet – RMI over Inter-ORB
Protocol.

1. RMI – OVERVIEW
Remote Method Invocation (RMI) is a Java technology that allows an object in one JVM to invoke methods on an
object located in another JVM, even across different computers.
It follows a Client-Server Model, enabling distributed computing where different applications communicate over a
network.
The communication between client and server is handled by using two intermediate objects: Stub object (on client
side) and Skeleton object (on server-side) as also can be depicted from below diagram as follows,

Figure1: Working of RMI


Key Components of RMI
1. Client – Requests a method execution on a remote object.
2. Server – Hosts the remote object and executes the requested method.
3. RMI Registry – A directory service where the server registers remote objects so clients can locate them.
4. Stub & Skeleton –
o Stub (Client-side Proxy): Represents the remote object locally.
o Skeleton (Server-side Proxy): Communicates with the actual remote object.

1.1 Architecture of an RMI Application


In an RMI application, we write two programs, a server program (resides on the server) and a client program (resides
on the client).
 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.
Let us now discuss the components of RMI architecture.
 Transport Layer – This layer connects the client and the server. It manages the existing connection and also
sets up new connections.
 Stub – A stub is an object at client. It resides in the client system; it acts as a gateway for the client program.
 Skeleton – This is an 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.
1.2 Working of an RMI Application
The following points summarize how an RMI application works –
 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. The result is passed all the way back to the client.
1.3 Marshalling and Unmarshalling
Whenever a client invokes a method that accepts parameters on a remote object, the parameters are bundled into a
message before being sent over the network. These parameters may be of primitive type or objects. In case of primitive
type, the parameters are put together and a header is attached to it. In case the parameters are objects, then they are
serialized. This process is known as marshalling.

At the server side, the packed parameters are unbundled and then the required method is invoked. This process is
known as unmarshalling.
1.4 RMI Registry
RMI registry 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 1ebind() 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).
1.5 Goals of RMI
Following are the goals of RMI –
 To minimize the complexity of the application.
 To preserve type safety.
 Distributed garbage collection.
 Minimize the difference between working with local and remote objects.

2. DEVELOPING APPLICATIONS WITH RMI


Step 1: Define the Remote Interface
 Create an interface that extends java.rmi.Remote.
 Declare remote methods that may throw RemoteException.
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Calculator extends Remote


{
int add(int a, int b) throws RemoteException;
int subtract(int a, int b) throws RemoteException;
}

Step 2: Implement the Remote Object


 Implement the interface.
 Extend UnicastRemoteObject to make the object available remotely.
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class CalculatorImpl extends UnicastRemoteObject implements Calculator


{
protected CalculatorImpl() throws RemoteException { super(); }

public int add(int a, int b) throws RemoteException { return a + b; }

public int subtract(int a, int b) throws RemoteException { return a - b; }


}

Step 3: Create and Bind the RMI Server


 Instantiate and register the remote object.
 Use LocateRegistry.createRegistry(port) to create an RMI registry.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class CalculatorServer


{
public static void main(String[] args)
{
try { Calculator calculator = new CalculatorImpl(); Registry registry = LocateRegistry.createRegistry(1099);
registry.rebind("CalculatorService", calculator); System.out.println("Calculator Server is Running..."); }
catch (Exception e) { e.printStackTrace(); }
}
}

Step 4: Develop the Client


 Lookup the remote object using LocateRegistry.getRegistry().
 Invoke remote methods.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class CalculatorClient


{
public static void main(String[] args)
{
try { Registry registry = LocateRegistry.getRegistry("localhost", 1099);
Calculator calculator = (Calculator) registry.lookup("CalculatorService");
int sum = calculator.add(5, 3); int difference = calculator.subtract(9, 4);
System.out.println("Sum: " + sum); System.out.println("Difference: " + difference);
}
catch (Exception e) { e.printStackTrace(); }
}
}

Step 5: Compile and Run


Compile all Java files
javac *.java

Start the RMI Registry


rmiregistry &

Run the Server


java CalculatorServer

Run the Client


java CalculatorClient

Output
Calculator Server is Running...
Sum: 8
Difference: 5

3. STUB & SKELETONS


 The RMI provides remote communication between the applications using two objects STUB and SKELETON.

 RMI uses STUB and SKELETONS object for communication with the remote object.
 A remote object is an object whose method can be invoked from another JVM.

STUB
The Stub is an object, acts as a gateway for the client’s side. The entire outgoing requests are routed through it. It resides
at the Client side and represents the remote object. When the caller invokes method on the Stub objects, it does the
following task.
i) It initiates a connection with remote Virtual Machine (JVM).
ii) It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM.)
iii) It waits for the result.
iv) It reads (unmarshals) the return value or exception
v) It finally, returns the value to the caller.

SKELETONS
The Skeletons is an object, acts as a gateway for the server side object. All the incoming requests are routed through it.
When the Skeleton receives the incoming requests, it does the following tasks:
i) It reads the parameter for the remote method.
ii) It invokes the method on the actual remote objects.
iii) It writes and transmits (marshals) the result to the caller.

The original implementation depends on Java Virtual Machine, class representation mechanism and it thus only Supports
Making calls from one JVM to another. The protocol underlying this Java only implementation is known as JAVA
Remote Method Protocol (JRMP).
In order to support code running in a non-JVM context, programmers later developed a COBRA version. Usage
of the term RMI may denote solely the programming interface or may signify both the API and JRMP, IIOP or another
implementation, whereas the term RMI-IIOP specifically denotes the RMI interface delegating most of the functionality
to the supporting COBRA implementation.
The basic idea of the JAVA RMI, the distributed garbage-collection protocol, and much of the architecture underlying
the original sun implementation, come from the “network objects”.

4. REGISTERING REMOTE OBJECTS IN RMI


The RMI registry is a simple server-side name server that allows remote clients to get a reference to a remote object.
It typically is used to locate only the first remote object an RMI client needs to talk to. Then, that first object in turn,
provides application-specific support getting references for other objects.

For example, the reference can be obtained as a parameter to, or a return value from, another remote method call.
Once a remote object is registered in the rmiregistry, clients can:
 obtain a remote object reference (e.g., by looking it up in the rmiregistry)
 Remotely invoke methods on the object.

For example, the following code binds the name "HelloServer" to a reference for the remote object:
Naming.rebind("HelloServer", obj);

5. WRITING RMI CLIENT PROGRAM THAT USES THE REMOTE SERVICE


The client part of the distributed Hello World example remotely invokes the sayHello method in order to get the string
"Hello world!", which is output when the client runs. Here is the code for the client:
import java.rmi.RMISecurityManager;
import java.rmi.Naming;
import java.rmi.RemoteException;
public class HelloClient
{
public static void main(String arg[])
{
String message = "blank";

// I download server's stubs ==> must set a SecurityManager


System.setSecurityManager(new RMISecurityManager());

try
{
Hello obj = (Hello) Naming.lookup( "//" +
"lysander.cs.ucsb.edu" +
"/HelloServer"); //objectname in registry
System.out.println(obj.sayHello());
}
catch (Exception e)
{
System.out.println("HelloClient exception: " + e.getMessage());
e.printStackTrace();
}
}
}

set the security manager, so that the client can download the stub code.
Get a reference to the remote object implementation (advertised as "HelloServer") from the server host's rmiregistry.
Invoke the remote sayHello method on the server's remote object
The constructed URL-string that is passed as a parameter to the Naming.lookup method must include the server's
hostname.

6. PUSHING DATA FROM AN RMI SERVLET IN JAVA


Remote Method Invocation (RMI) is a Java technology that enables objects in different JVMs (Java Virtual
Machines) to communicate remotely. When used with Servlets, RMI can push data from a Java server to remote
clients.

How Does Pushing Data Work in an RMI Servlet?


A Servlet in Java typically handles HTTP requests synchronously. However, when combined with RMI, it can push
data to remote applications asynchronously. This is useful for real-time data updates in distributed systems, such as:
✅ IoT applications – Sending sensor data updates to remote clients.
✅ Stock market apps – Pushing real-time stock prices.
✅ Live notifications – Delivering alerts to multiple remote users.

Steps to Push Data from an RMI Servlet


1. Create an RMI Interface – Define the remote methods.
2. Implement the RMI Server – The logic that sends data.
3. Expose an RMI Servlet – The web entry point that interacts with the client.
4. Develop the RMI Client – A remote system that receives the pushed data.

Step 1: Create the RMI Interface


Define the remote methods that clients can call.
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface DataPushService extends Remote {


void sendUpdate(String message) throws RemoteException;
}

Step 2: Implement the RMI Server (Data Publisher)


This class pushes data to registered clients.
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;

public class DataPushServiceImpl extends UnicastRemoteObject implements DataPushService {


private List<DataPushClient> clients = new ArrayList<>();

protected DataPushServiceImpl() throws RemoteException {}

public void registerClient(DataPushClient client) throws RemoteException {


clients.add(client);
}

@Override
public void sendUpdate(String message) throws RemoteException {
for (DataPushClient client : clients) {
client.receiveUpdate(message); // Push data to clients
}
}
}

Step 3: Expose an RMI Servlet


A Servlet that interacts with remote clients and calls RMI methods.
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.rmi.Naming;

public class DataPushServlet extends HttpServlet {


private DataPushService dataService;

@Override
public void init() throws ServletException {
try {
dataService = (DataPushService) Naming.lookup("//localhost/DataPushService");
} catch (Exception e) {
throw new ServletException("RMI lookup failed", e);
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException {
String message = request.getParameter("message");
try {
dataService.sendUpdate(message); // Push data to RMI clients
response.getWriter().write("Data pushed successfully!");
} catch (Exception e) {
response.getWriter().write("Error pushing data: " + e.getMessage());
}
}
}

Step 4: Create the RMI Client (Receiver)


This client receives data pushed from the RMI Server.
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface DataPushClient extends Remote {


void receiveUpdate(String message) throws RemoteException;
}
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class DataPushClientImpl extends UnicastRemoteObject implements DataPushClient {


protected DataPushClientImpl() throws RemoteException {}

@Override
public void receiveUpdate(String message) throws RemoteException {
System.out.println("Received update: " + message);
}
}

Step 5: Start the RMI Server


Run the RMI registry and start the server:

import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;

public class RMIServer {


public static void main(String[] args) {
try {
LocateRegistry.createRegistry(1099); // Start RMI Registry
DataPushServiceImpl service = new DataPushServiceImpl();
Naming.rebind("//localhost/DataPushService", service);
System.out.println("RMI DataPushService started...");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Step 6: Test the RMI Push Mechanism


 Start the RMI Server (RMIServer.java)
 Deploy the DataPushServlet in Tomcat or any JEE server
 Run the DataPushClient to listen for updates
 Send a POST request to the Servlet (localhost:8080/DataPushServlet?message=New Data Available!)
The client should receive:
sql
Received update: New Data Available!
7. RMI over Inter-ORB Protocol (RMI-IIOP) in Java
What is RMI-IIOP?
RMI over IIOP (RMI-IIOP) is a Java technology that allows Remote Method Invocation (RMI) to communicate
using the Internet Inter-ORB Protocol (IIOP) instead of Java’s native RMI protocol (JRMP). It enables Java
applications to interoperate with CORBA (Common Object Request Broker Architecture) systems.

Figure 1-1 RMI object relationships


Why Use RMI-IIOP?
✅ Interoperability – Java applications can communicate with non-Java CORBA applications.
✅ Standard Protocol – Uses IIOP, a standard internet protocol for distributed objects.
✅ Security & Scalability – Better suited for enterprise-grade, multi-language systems.
✅ JEE Integration – Works with Enterprise JavaBeans (EJB) and JNDI.

RMI vs. RMI-IIOP


Feature RMI (JRMP) RMI-IIOP
Protocol JRMP (Java Remote Method Protocol) IIOP (CORBA-based)
Interoperability Java-only Works with Java & CORBA systems
Performance Optimized for Java Standardized, but slightly slower
Security Java Security Model Uses CORBA security mechanisms
Use Cases Java-to-Java communication Java-to-CORBA, Java-to-other languages

How RMI-IIOP Works


1. Define a Remote Interface – Same as RMI.
2. Generate IIOP Stubs and Skeletons – Use rmic -iiop.
3. Use JNDI for Naming Services – Instead of rmiregistry, it binds services via CORBA Naming Service.
4. Clients Lookup the Remote Object – Clients call remote methods using IIOP.

Step-by-Step Implementation of RMI-IIOP


1. Define the Remote Interface
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Calculator extends Remote {


int add(int a, int b) throws RemoteException;
}

2. Implement the RMI-IIOP Server


import javax.rmi.PortableRemoteObject;
import java.rmi.RemoteException;
public class CalculatorImpl extends PortableRemoteObject implements Calculator {
protected CalculatorImpl() throws RemoteException {
super(); // Required for IIOP
}

public int add(int a, int b) throws RemoteException {


return a + b;
}
}

3. Create the RMI-IIOP Server


import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Properties;

public class CalculatorServer {


public static void main(String[] args) {
try {
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.cosnaming.CNCtxFactory");
props.put(Context.PROVIDER_URL, "iiop://localhost:1050");

InitialContext ctx = new InitialContext(props);


CalculatorImpl calcObj = new CalculatorImpl();

ctx.rebind("CalculatorService", calcObj);
System.out.println("RMI-IIOP Server Started...");
} catch (Exception e) {
e.printStackTrace();
}
}
}

4. Implement the RMI-IIOP Client


import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Properties;

public class CalculatorClient {


public static void main(String[] args) {
try {
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.cosnaming.CNCtxFactory");
props.put(Context.PROVIDER_URL, "iiop://localhost:1050");

InitialContext ctx = new InitialContext(props);


Calculator calculator = (Calculator) ctx.lookup("CalculatorService");

int result = calculator.add(10, 20);


System.out.println("Addition Result: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Running RMI-IIOP
1. Start the CORBA Naming Service:
orbd -ORBInitialPort 1050

2. Compile the Code:

javac Calculator.java CalculatorImpl.java CalculatorServer.java CalculatorClient.java

3. Generate Stubs & Skeletons (optional in Java 8+):


rmic -iiop CalculatorImpl

4. Start the Server:


java CalculatorServer

5. Run the Client:


java CalculatorClient

--------- End of Unit-III -------

You might also like