Give a man a program, frustrate him for a day. <i>Teach</i> a man to program, frustrate him for a lifetime.

RMI: Hello, world!

Source

The interface


Hello.java
package api;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Hello extends Remote
{
    public static String SERVICE_NAME = "HelloService";

    String hello() throws RemoteException;
}


The implementation


HelloServer.java
package server;

import api.Hello;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

class HelloServer extends UnicastRemoteObject implements Hello
{
    HelloServer() throws RemoteException {} // "export" HelloImpl

    @Override
    public String hello() { return "Hello world!"; }

    public static void main(String[] args) throws Exception
    {
        // construct & set a security manager (unnecessary in this case)
        System.setSecurityManager( new SecurityManager() );

        // instantiate a server object
        Hello hello = new HelloServer(); // can throw RemoteException

        // construct an rmiregistry within this JVM using the default port
        Registry registry = LocateRegistry.createRegistry( 1099 );

        // bind server in rmiregistry. Can throw exceptions. See api.
        registry.rebind( Hello.SERVICE_NAME, hello );

        System.out.println("HelloImpl.main: Ready.");
    }
}

The client


HelloClient.java
package client;

import api.Hello;
import java.rmi.Naming;

class HelloClient
{
    public static void main( String[] args ) throws Exception
    {
        System.setSecurityManager( new SecurityManager() );
        String serverDomainName = "localhost";
        String url = "//" + serverDomainName + "/" + Hello.SERVICE_NAME;

        // Can throw exceptions - see API for java.rmi.Naming.lookup
        Hello hello = (Hello) Naming.lookup( url );

        System.out.println( hello.hello() ); // can throw RemoteException
    }
}

Running

For example, the command below runs a Java application called Application. In this case, the system expects the policy file called policy to be in the directory where the java command executes.

NB: Discussion of codebase is deferred; it is unnecessary for this Hello, world example.



 cappello@cs.ucsb.edu © Copyright 2010 Peter Cappello                                           2015.03.26