img
Remote Method Invocation (RMI)
Remote Method Invocation (RMI) allows a Java object that executes on one machine to invoke a
method of a Java object that executes on another machine. This is an important feature,
because it allows you to build distributed applications. While a complete discussion of RMI is
outside the scope of this topic, the following example describes the basic principles involved.
A Simple Client/Ser ver Application Using RMI
This section provides step-by-step directions for building a simple client/server application
by using RMI. The server receives a request from a client, processes it, and returns a result.
In this example, the request specifies two numbers. The server adds these together and
returns the sum.
Step One: Enter and Compile the Source Code
This application uses four source files. The first file, AddServerIntf.java, defines the remote
interface that is provided by the server. It contains one method that accepts two double
arguments and returns their sum. All remote interfaces must extend the Remote interface,
which is part of java.rmi. Remote defines no members. Its purpose is simply to indicate that
an interface uses remote methods. All remote methods can throw a RemoteException.
import java.rmi.*;
public interface AddServerIntf extends Remote {
double add(double d1, double d2) throws RemoteException;
}
The second source file, AddServerImpl.java, implements the remote interface. The
implementation of the add( ) method is straightforward. All remote objects must extend
UnicastRemoteObject, which provides functionality that is needed to make objects
available from remote machines.
import java.rmi.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject
implements AddServerIntf {
public AddServerImpl() throws RemoteException {
}
public double add(double d1, double d2) throws RemoteException {
return d1 + d2;
}
}
The third source file, AddServer.java, contains the main program for the server machine.
Its primary function is to update the RMI registry on that machine. This is done by using the
rebind( ) method of the Naming class (found in java.rmi). That method associates a name
with an object reference. The first argument to the rebind( ) method is a string that names the
server as "AddServer". Its second argument is a reference to an instance of AddServerImpl.
import java.net.*;
import java.rmi.*;
public class AddServer {
public static void main(String args[]) {
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home