Java Reference
In-Depth Information
the requirement of placing the remote calls within a try/catch block. The
registry lookup is handled by the following code snippet:
// Get a reference to the RMIExampleServer.
RMIExampleInterface server = null;
try {
// Lookup the server.
String server - name ="//localhost:3001/rmi-example-server";
server = (RMIExampleInterface) Naming.lookup (server - name);
} // try
catch (NotBoundException nbe) {...}
catch (MalformedURLException mue) { ... }
catch (RemoteException re) { ... }
Notice that we have used the same name in the lookup() call that the server
was bound under. This example is set up to run both client and server on the
same machine, so localhost works for both. If the server were running on a
remote machine, then that machine would be specified instead of localhost .
Of course the proper port number must be specified as well, and the final part of
the name must match the original rmi-example-server name used when
the server was bound into the registry. Naming.lookup() must be enclosed
in a try/catch block as well. There are several exceptions that could occur,
including NotBoundException ,which is thrown if the requested server name
is not found in the RMI registry running on the indicated host and port num-
ber. Other possible exceptions are MalformedURLException and the usual
RemoteException .Ifthe lookup fails, then null is returned, so one should
always check for null before continuing.
Naming.lookup() returns a Remote interface, which must be cast into
the RMIExampleInterface that we really want. Notice that it is the inter-
face , not the remote RMIExampleImpl implementation class that we need.
Since every remote method implemented in the implementation class is declared
in the interface, we can access all those remote methods through the interface
in the normal Java fashion. This interface object reference actually refers to
the client-side stub, and the RMI system handles all the actual communica-
tion from client, through stub and skeleton, to the remote implementation class.
This object reference can be, and often is, thought of as a reference to the
remote server implementation. In fact, we refer to it as “server” in the example
above.
If a non-null reference to the desired server is received, then we can proceed
to making a remote method call as follows:
try {
server.method1 ( " hello from client " );
 
Search WWH ::




Custom Search