2. RMI
Remote method invocation(RMI) allow a java object to invoke
method on an object running on another machine. RMI
provide remote communication between java program.
RMI is used for building distributed application.
Concept of RMI application
A RMI application can be divided into two part,Client program
and Server program. A Server program creates some
remote object, make their references available for the
client to invoke method on it. A Client program make
request for remote objects on server and invoke method on
them. Stub and Skeleton are two important object used for
communication with remote object.
3. Stub and Skeleton
Stub act as a gateway for Client program. It resides on Client side and communicate with
Skeleton object. It establish the connection between remote object and transmit request to
it.
Skeleton object resides on server program. It is responsible for
passing request from Stub to remote object.
4. Steps to Implement RMI
• 1. write an interface that describes operations with
the name
ReceiveMessageInterface.java
import java.rmi.*;
public interface ReceiveMessageInterface extends
Remote
{
void receiveMessage(String x) throws
RemoteException;
}
6. Contd….
import java.rmi.*;
import java.rmi.registry.*;
import java.net.*;
public class RmiClient
{
static public void main(String args[])
{
ReceiveMessageInterface rmiServer;
Registry registry;
String serverAddress=args[0];
String serverPort=args[1];
String text=args[2];
System.out.println("sending "+text+" to "+serverAddress+":"+serverPort);
try{
registry=LocateRegistry.getRegistry(
serverAddress,
(new Integer(serverPort)).intValue()
);
7. Contd…
// look up the remote object
rmiServer=
(ReceiveMessageInterface)(registry.lookup("rmiServer"));
// call the remote method
rmiServer.receiveMessage(text);
}
catch(RemoteException e){
e.printStackTrace();
}
catch(NotBoundException e){
e.printStackTrace();
}
}
}
8. 4. Compile the RmiClient.java file.
C:>javac RmiClient.java
5. Write the Server side program with a file
name RmiServer.java
9. import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
import java.net.*;
public class RmiServer extends java.rmi.server.UnicastRemoteObject
implements ReceiveMessageInterface
{
int thisPort;
String thisAddress;
Registry registry;
public void receiveMessage(String x) throws RemoteException
{
System.out.println(x);
}
10. public RmiServer() throws RemoteException
{
try{
// get the address of this host.
thisAddress=
(InetAddress.getLocalHost()).toString();
}
catch(Exception e){
throw new RemoteException("can't get inet
address.");
}
13. 5. Compile the file RmiServer.java
C:> javac RmiServer.java
6. Compile the RmiServer with rmic:
C:>rmic RmiServer
7. Start RmiServer at server side
C:> java RmiServer
8. Start client at client side
C:> java RmiClient serverip serverport message