Recipe 22.1 Defining the RMI Contract


You want to define the communications exchange between client and server.


Define a Java interface.


RMI procedures are defined using an existing Java mechanism: interfaces. An interface is similar to an abstract class, but a class can implement more than one interface. RMI remote interfaces must be subinterfaces of java.rmi.Remote. All parameters and return values must be either primitives (int, double, etc.), or implement Serializable (as do most of the standard types like String). Or, as we'll see in Recipe 22.5, they can also be Remote.

Figure 22-1 shows the relationships between the important classes involved in an RMI implementation. The developer need only write the interface and two classes, the client application and the server object implementation. The RMI stub or proxy and the RMI skeleton or adapter are generated for you by the rmic program (see Recipe 22.3), while the RMI Registry and other RMI classes at the bottom of the figure are provided as part of RMI itself.

Example 22-1 is a simple RemoteDate getter interface, which lets us find out the date and time on a remote machine.

Example 22-1.
package darwinsys.distdate; import java.rmi.*; import java.util.Date; /** A statement of what the client & server must agree upon. */ public interface RemoteDate extends java.rmi.Remote {     /** The method used to get the current date on the remote */     public Date getRemoteDate( ) throws java.rmi.RemoteException;     /** The name used in the RMI registry service. */     public final static String LOOKUPNAME = "RemoteDate"; }

Figure 22-1. RMI overview

This file must list all the methods that will be callable from the server by the client. The lookup name is an arbitrary name that is registered by the server and looked up by the client to establish communications between the two processes (when looked up by the client it will normally be part of an rmi: URL). While most authors just hardcode this string in both programs, I find this error-prone, so I usually include the lookup name in the interface .

"So interfaces can contain variables?" you ask. No variables indeed, but interfaces may contain nonvariable (final) fields such as the field LOOKUPNAME in Example 22-1. Putting the lookup name here ensures that both server and client really agree, and that is what this interface is all about, after all. I've seen other developers waste a considerable amount of time tracking down spelling mistakes in the lookup names of various remote services, so I prefer doing it this way.

Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: