4.4.2 The Server Implementation

In creating a server, one essentially creates a thread which waits upon a socket for packets to come in. This is done for you in the RemoteUnicastObject class, so that one need only extend this class for the code to work.

There is a bit of boilerplate to create an appropriate security manager for the stub code that is going to be loaded in, and then we set up the name in the rmiregistry by which we can be called.

The rmiregistry is a bootstrapping mechanism through which remote objects can be located. It is a daemon which is run on the local machine. Remote objects which are created and need to be accessible through some well-known name bind themselves to the name within the rmiregistry through the java.rmi.Naming class.

Create a file called UserIdImpl with the following code. Substitute for UserId and ianw as appropriate.

import java.rmi.*;
import java.rmi.server.*;
import java.net.*;
 
public class IanwImpl extends UnicastRemoteObject implements Ianw  {
 
    public IanwImpl() throws RemoteException {
        // We can pass through the port we want to start the server on
        // through to the super constructor.  Note that 8001 is chosen
        // since it is one of the open ports in 5A17/18
        super(8001);
    }
 
    public String sayHello() throws RemoteException {
        return("Hello World!");
    }
 
    public static void main(String arg[]) {
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
        }
        try {
            IanwImpl server = new IanwImpl();
            String hostName = InetAddress.getLocalHost().getHostName();
            Naming.rebind("//" + hostName + "/" + Ianw.rmiName, server);
            System.out.println("IanwImpl bound");
        } catch (Exception e) {
            System.err.println("IanwImpl exception " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Ian Wakeman 2005-02-22