Michael Elhadad

Software Engineering - Fall 1999


Lecture 5: Distributed Objects (Part 1) -- Java RMI

Selection of Infrastructure: Platform for development of Distributed Applications.

Motivation

Candidates for Distributed Architecture Platforms

Basic Concepts: Distributed Objects

First RMI Example (Nelson 98)

Objective: a Line Printer server object.
public interface LinePrinter
  {
    public void type(String line)
  }
RMI Requirements:
public interface LinePrinter
    extends java.rmi.Remote
  {
    public void type(String line)
      throws java.rmi.RemoteException;
  }
RMI uses the extends java.rmi.Remote as an indication that an object is distributed. All operations on remote objects can potentially fail on the network. The exception RemoteException indicates this.
How parameters are passed
If parameter is an instance of a distributed object, an object reference is passed. All operations to that object are invoked remotely. If parameter is not a distributed object, it is serialized using Java's standard Object Serialization.
try  {
  printer.type("Hello!");
} 
catch (java.rmi.RemoteException e) {
  System.err.println("Cannot connect.");
  e.printStackTrace();
}
Objects Implementation
public class LinePrinterImpl
  extends java.rmi.server.UnicastRemoteObject
  implements LinePrinter
{
  public LinePrinterImpl()
    throws java.rmi.RemoteException
  {
  }
  
      
  public void type(String s)
    throws java.rmi.RemoteException
  {
    System.out.println(s);
  }
}
Distributed Object Compilation
  1. Compile Implementation as usual (javac LinePrinterImpl).
  2. Generate stub and skeleton automatically: (rmic LinePrinterImpl)
Writing a Server
import java.rmi.*;


public class PrintServer
{
  public static void main(String[] args)
  {
    System.setSecurityManager(new RMISecurityManager());

    try
      {
        LinePrinter printer = new LinePrinterImpl();
        Naming.rebind( "LinePrinter", printer );
        System.out.println("PrintServer is ready.");
      }
    catch (Exception e)
      {
        System.out.println( "Error: " + e );
        e.printStackTrace();
      }
  }
}
Writing a Client

import java.io.*;
import java.rmi.*;


public class PrintClient
{
  public static void main(String[] args)
  {
    try
      {
        LinePrinter printer = 
          (LinePrinter)Naming.lookup("//localhost/LinePrinter");
 
        BufferedReader r = new
          BufferedReader(new InputStreamReader(System.in));

        String nextLine = r.readLine();
        
        while (nextLine != null)
          {
            printer.type( nextLine );
            nextLine = r.readLine();
          }
    
      }
    catch (Exception e)
      {
        System.err.println("Error: " + e);
        e.printStackTrace();
      }
  }
}
Naming Service and rmiregistry

Running the Example

The files needed are:

References


Java Tutorial on RMI

Java RMI example



Last modified Apr 25th, 1999 Michael Elhadad