Client Implementation
The client in this example remotely invokes the getMessage()
method in order to get the string "Hello World". Here is the code:
Listing 3.3 (HelloClient.java)
import java.rmi.*;
import java.net.MalformedURLException;
//Client implementation
public class HelloClient {
//main method
public static void main(String []helloClient) {
try{
//get a reference to the stub
HelloInterface server =
(HelloInterface)Naming.lookup("rmi://localhost:1099/Server");
//Call the remote method
String msg = server.getMessage();
System.out.println(msg);
}catch(RemoteException ex) {
System.out.println("Error " +ex.getMessage());
}catch(MalformedURLException ex) {
System.out.println("Error " +ex.getMessage());
}
catch(NotBoundException ex) {
System.out.println("Error " +ex.getMessage());
}
}
}
Explanation of
Code
Import the necessary packages.
import
java.rmi.*;
import java.net.MalformedURLException;
The client does not need to extend UnicastRemoteObject
or implement any remote interface unless it is also exporting
some objects. Here is the HelloClient
class declaration:
public
class
HelloClient {
This client will run as a stand alone application so it must declare
a main() method.
public static void main(String []helloClient) {
try{
//get a reference to the stub
HelloInterface server =
(HelloInterface)Naming.lookup("rmi://localhost:1099/Server");
//Call the remote method
String msg = server.getMessage();
System.out.println(msg);
}catch(RemoteException ex) {
System.out.println("Error " +ex.getMessage());
}catch(MalformedURLException ex) {
System.out.println("Error " +ex.getMessage());
} catch(NotBoundException ex) {
System.out.println("Error " +ex.getMessage());
}
}
First, the client gets a reference to the remote object implementation
from the server(s) registry. The Naming.lookup()
method takes a URL-formatted string. It returns a stub, for the
remote object associated with the specified name. The lookup()
method may throw a number of exceptions:
- NotBoundException - if name
is not currently bound
- RemoteException - if registry
could not be contacted
- MalformedURLException -
if the name is not an appropriately formatted URL
HelloInterface server
= (HelloInterface)Naming.lookup("Server");
After execution of the above statement, the variable "server" will
contain a reference to an instance of the stub class that actually handles
the client side RMI. Now the client can invoke methods on the remote
object.
String msg = server.getMessage();
Finally, the program prints "HelloWorld" returned by the server.
System.out.println(msg);
The code for this example is complete.
Figure 3.3

|