Chapter 5 Remote Procedure Call - and - Remote Method Invocation
Chapter 5 Remote Procedure Call - and - Remote Method Invocation
All Rights
Reserved.
Outline
5.1. Overview of RPC & RMI
5.2. Stub and skeleton
5.3. The RMI Registry
5.4. The Remote Interface
5.5. Implementing RMI
8
In Java, the Remote Interface is an interface that enables objects to
be accessed remotely, across different Java Virtual Machines
(JVMs) or even across different machines.
Remote Interfaces are used in distributed applications where
different parts of the application are running on different machines
and need to communicate with each other.
Remote Interfaces in Java are implemented using the Java Remote
Method Invocation (RMI) framework, which provides a
mechanism for invoking methods on objects running in different
JVMs.
To create a Remote Interface in Java, you need to define an
interface that extends the java.rmi.Remote interface and declare
the methods that can be invoked remotely. For example:
9
import java.rmi.Remote;
import java.rmi.RemoteException;
11
On the client-side, you can then access the remote object by
looking it up in the RMI registry and invoking its methods as
if it were a local object.
The RMI framework takes care of the details of marshalling
and unmarshalling parameters and return values across the
network. For example:
12
import java.rmi.Naming;
import java.rmi.RemoteException;
public class MyRemoteClient {
public static void main(String[] args) {
try {
MyRemoteInterface remoteObject = (MyRemoteInterface)
Naming.lookup("rmi://localhost/MyRemoteObject");
remoteObject.doSomething();
} catch (Exception e) {
e.printStackTrace();
}
}
}
13
To implement RMI (Remote Method Invocation) in Java, you
need to follow the following steps:
1.Define the Remote Interface: The first step is to define the
remote interface that specifies the methods that can be invoked
remotely. The interface should extend the java.rmi.Remote
interface and each method should declare
java.rmi.RemoteException. For example:
import java.rmi.Remote;
import java.rmi.RemoteException;
17
Create the Client: Finally, you can create the client that accesses the
remote object by looking it up in the RMI registry using the
java.rmi.Naming class. For example:
import java.rmi.Naming;
import java.rmi.RemoteException;
public class MyRemoteClient {
public static void main(String[] args) {
try {
MyRemoteInterface remoteObject = (MyRemoteInterface)
Naming.lookup("rmi://localhost/MyRemote");
18
String result = remoteObject.sayHello("Alice");
System.out.println(result);
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
19
When you run the server and client, the output should be:
20