Professional Documents
Culture Documents
Java RMI (Remote Method Invocation)
Java RMI (Remote Method Invocation)
Java RMI (Remote Method Invocation)
My Machine
My Object
Today’s World...
Network and Distributed Objects
My Machine Remote
Machine
Local
Remote
Objects
Objects
Introduction
Remote Method Invocation (RMI) provides a
framework for building distributed Java
systems.
12
The basic steps
Create the interface.
Define a class that implements this interface.
Create the server process.
Create the client process.
13
1. Create the interface
This interface should import package java.rmi
and must extend interface Remote , which is a
‘tagging’ interface that contains no methods.
The interface definition for our example must
specify the signature for method getGreeting,
which is to be made available to clients.
This method must declare that it throws A
RemoteException
import java.rmi.*;
public interface Hello extends Remote {
public String getGreeting() throws
RemoteException;
}
2. Define a class that implements this interface
The implementation file should import
packages java.rmi and java.rmi.server .
16
import java.rmi.*;
import java.rmi.server.*;
}
public String getGreeting() throws RemoteException
{
return ("Hello there!");
}
}
17
3. Create the server process
The server creates object(s) of the above
implementation class and registers them with a naming
service called the registry
The registry is implemented by a class called Naming
and an application called rmiregistry. The rmiregistry
application must be running on a host before you start a
Java program that wants to advertise in the registry.
23
[Note that, before Java SE 5, it was necessary
to compile the implementation class (yes,
compile a .class file!) with the rmic compiler
thus:
rmic HelloImpl
This would generate both a stub file and a
skeleton file. However, this stage is no longer
required.]
2. Start the RMI registry
rmiregistry
When this is executed, the only indication that
anything has happened is a change in the command
window’s title.
25
3. Open a new window and run the server
From the new window, invoke the Java
compiler:
java HelloServer
26
4. Open a third window and run the client
Again, invoke the Java compiler:
java HelloClient
27
Example 2
Step 1: Defining the Remote Interface
import java.rmi.*;
}
//Implement the remote methods
public int sum(int a,int b) throws RemoteException
{
return a + b;
}
. . .
Use java.rmi.Naming class to bind the server name to
registry.
public static void main(String args[])
{
try
{
//create a local instance of the object
System.out.println("Server waiting.....");
}
catch (java.net.MalformedURLException me){
System.out.println("Malformed URL: " + me.toString());
}
catch (RemoteException re) {
System.out.println("Remote exception: " + re.toString());
}
}
Step 3: Develop the client program
import java.rmi.*;
import java.rmi.server.*;