Java RMI

Jussi Pohjolainen

TAMK University of Applied Sciences » ICT

Intro to RMI

Overview

Locating and Communicating

Locating and Communicating

RMI Overview

RMI Overview

Implementing RMI System

Class Diagram of the Server - side

RMI Overview

UnicastRemoteObject and Remote - interface

Parameter passing

Stub and Skeleton

In Practice: Creating a simple RMI system

  1. Define a interface that holds remote methods. Remember that every method must throw java.rmi.RemoteException and the interface must inherit java.rmi.Remote
  2. Create RemoteObject class that implements the interface implemented above. Remember that this class must inherit java.rmi.UnicastRemoteObject and it's default constructor must throw java.rmi.RemoteException
  3. Create Server class that creates the RemoteObject and binds it to the rmiregistry
  4. Create a client that locates RemoteObject from rmiregistry and calls it's remote methods
  5. (Optional) create stub and skeleton classes using rmic compiler
  6. Start rmiregistry, server and client

1) Define interface

import java.rmi.*;

public interface Hello extends Remote {
    String sayHello() throws RemoteException;
}

2) Create Remote Object

import java.rmi.*;
import java.rmi.server.*;

public class RemoteObject extends UnicastRemoteObject 
     implements Hello {
    
    public RemoteObject() throws RemoteException { }
    
    public String sayHello() throws RemoteException {
        return "Hello from another JVM!"; 
    }
}

3) Create Server

import java.rmi.*;
import java.rmi.server.*;

public class HelloServer {
    public static void main(String [] args) {
        try {
            RemoteObject remoteobject = new RemoteObject();
            Naming.rebind("donaldduck", remoteobject);
            System.out.println("Remote object is now 
                bind to the rmi-registry");
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}

4) Create Client

import java.rmi.*;
import java.rmi.server.*;

public class HelloClient {
    public static void main(String [] args) {
        try {
            Hello external = 
                (Hello)Naming.lookup("//localhost/donaldduck");
            String message = external.sayHello();
            System.out.println(message);
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}

5) Create Stub and Skeleton classes

> rmic -v1.1 RemoteObject
// creates RemoteObject_Skel.class and RemoteObject_Stub.class

6) Start the application

> rmiregistry
> java HelloServer
> java HelloClient