The Client Program
Home ] Up ] The Remote Interface ] The Remote Implementation ] [ The Client Program ] Running The Example ]

 

 

Here's the client program:

package rmiClient;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import rmi.Hello;

/**
 * Client for Hello RMI server.
 *
 * @author Bryan Higgs
 * @version 1.0
 */
public class HelloClient
{
  /**
   * Main entry point for client
   * @param args the command line arguments
   *             args[0] contains the server hostname
   *             args[1] contains the port number for the registry
   */
  public static void main(String[] args)
  {
    // Determine server hostname
    String host = null;
    if (args.length > 0)
      host = args[0];
    
    // Determine the port number
    int port = 1099;  // the default port number for the registry
    if (args.length > 1)
    {
      try
      {
        port = Integer.parseInt(args[1]);
      }
      catch (NumberFormatException nfe)
      {
        System.err.println("Port number " + args[1] + " invalid");
        return;
      }
    }
    
    try
    {
      // Find the RMI registry
      Registry registry = LocateRegistry.getRegistry(host, port);
      // Look up the server
      Hello stub = (Hello) registry.lookup("Hello");
      
      // Call the server at the sayHello entry point.
      String response = stub.sayHello();
      System.out.println("Response: " + response);
    }
    catch (NotBoundException nbe)
    {
      nbe.printStackTrace();
    }
    catch (RemoteException re)
    {
      re.printStackTrace();
    }
  }
  
  /**
   * Creates a new instance of HelloClient
   * (Make private to disable constructor)
   */
  public HelloClient()
  {
  }
}

Note that we:

  1. Use the java.rmi.registry.LocateRegistry class to locate the registry (on the server machine), and then java.rmi.registry.Registry to look up the remote object in the RMI registry.
  2. Call the remote object by calling the stub's sayHello() method.
  3. Print out the response.
 
The page was last updated February 19, 2008