How to Write a Simple Server

and Client Using Java RMI

Here are some brief instructions to get you started writing a simple client and server that use Java(tm) Remote Method Invocation. In order to write a server, a client, and then run them, you need to do the following:

  1. Define a remote interface.

    A remote interface is one that extends java.rmi.Remote. Each method in a remote interface must have java.rmi.RemoteException in its throws clause. For an example of a simple remote interface, see the file Echo.java in the echo example directory.

  2. Implement the remote interface (the server).

    To implement a remote interface, your implementation class should extend the class java.rmi.UnicastRemoteServer.

    Your implementation class must either:

  3. Register the server in the registry.

    You may want to register an instance of a remote object with the registry so that clients can contact the remote object. Use the java.rmi.Naming class to bind a name to your server object (see EchoImpl.java for usage).

  4. Generate stubs for your remote object implementation class(es).

    The distribution contains a stub compiler called rmic. rmic takes the same command-line arguments as javac. In order to generate stubs, run the rmic compiler as follows:

    	  rmic classname
       
    If you want to put the generated files in a particular place, use the -d option, e.g.,

    	  rmic -d blah/classes className
       
  5. Write a client program.

    A simple client program could lookup the remote object using the Naming class (see EchoClient.java), and invoke methods on the remote object.

  6. Start the registry.

    You must start the registry on the hosts on which you will be running the remote object server(s):

              % java java.rmi.registry.RegistryImpl &
        
  7. Run your remote object server(s) and then your client(s).