Java Reference
In-Depth Information
CHAPTER 16
Remote Method Invocation
This chapter presents examples of using the remote method invocation (RMI)
capabilities of the
java.rmi
and
java.rmi.server
packages. Remote method invo-
cation is a powerful technology for developing networked applications without
having to worry about the low-level networking details. RMI transcends the client/
server model of computing with a more general remote object model. In this
model, the server defines objects that clients can use remotely. Clients invoke
methods of a remote object exactly as if it were a local object running in the same
virtual machine as the client. RMI hides the underlying mechanism for transporting
method arguments and return values across the network. An argument or return
value can be a primitive value or any
Serializable
object.
To develop an RMI-based application, you need to follow these steps:
•
Create an interface that extends the
java.rmi.Remote
interface. This interface
defines the exported methods that the remote object implements (i.e., the
methods the server implements and clients can invoke remotely). Each
method in this interface must be declared to throw a
java.rmi.RemoteExcep-
tion
, which is the superclass of many more specific RMI exception classes.
Every remote method must declare that it can throw a
RemoteException
,
because there are quite a few things that can go wrong during the remote
method invocation process over a network.
•
Define a subclass of
java.rmi.server.UnicastRemoteObject
(or sometimes a
related class) that implements your
Remote
interface. This class represents the
remote object (or server object). Other than declaring its remote methods to
throw
RemoteException
objects, the remote object doesn't need to do any-
thing special to allow its methods to be invoked remotely. The
Unicast-
RemoteObject
and the rest of the RMI infrastructure handle this automatically.
•
Write a program (a server) that creates an instance of your remote object.
Export the object, making it available for use by clients, by registering the
object by name with a registry service. This is usually done with the
java.rmi.Naming
class and the
rmir egistry
program. A server program may