Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

RMI

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 62

Java Remote Method Invocation (RMI)

Introduction
Java
Networking Distributed

Computing

Java Remote Method Invocation (RMI) Is an Inter-process Protocol for Java, Allowing Java Objects Living in Different Java Virtual Machines to Invoke Transparently Each Other's Methods. Since These Virtual Machines Can Be Running on Different Computers Anywhere on the Network, RMI Enables Objectoriented Distributed Computing. Java RMI Provides the Java Programmers With an Efficient, Transparent Communication Mechanism That Frees Them of All the Application-level Protocols Necessary to Encode and Decode Messages for Data Exchange.

RMI defined

What Is RMI?
Access

to Remote Objects Java-to-Java only Client-Server Protocol High-level API Transparent Lightweight

Examples of Use
Database

access Computations Any custom protocol

Related Technologies

RPC

(Remote Procedure Calls)

Developed by Sun Platform-specific


(Common Object Request Broker Architecture)

CORBA

Developed by OMG Access to non-Java objects (as well as Java)


(Distributed Common Object Model)

DCOM

Developed by Microsoft Access to Win32 objects


(Lightweight Directory Access Protocol)

LDAP

Finding resources on a network

Middleware Layers
Applications RPCs and RMIs, e.g., CORBA Request reply protocol External data representation Operating System Middleware layers= Provide support to the application

RMI=Remote Method Invocation CORBA=Common Object Request Brokerage Architecture

Part I: RMI Concepts

Remote Objects (Diagram)


Java Virtual Machine Java Virtual Machine

Client Object

TCP

Remote Object

RMI Layers
Java Virtual Machine Client Object Java Virtual Machine Remote Object

Stub

Skeleton

Remote Reference Layer

Remote Reference Layer

Transport Layer

TCP

Transport Layer

Remote Objects
Remote
Live

Objects

on server Accessed as if they were local

Registries
Name

and look up remote objects Servers can register their objects Clients can find server objects and obtain a remote reference A registry is a running process on a host machine

The RMI Registry

The Server Object Makes Methods Available for Remote Invocation by Binding It to a Name in the RMI Registry.
The Client Object, Can Thus Check for the Availability of a Certain Server Object by Looking up Its Name in the Registry.

The RMI Registry Thus Acts As a Central Management Point for Java-RMI. The RMI Registry Is Thus a Simple Name Repository. It Does Not Address the Problem of Actually Invoking Remote Methods.

Remote References and Interfaces


Remote
Refer

References

to remote objects Invoked on client exactly like local object references


Remote

Interfaces

Declare

exposed methods Implemented on client Like a proxy for the remote object

Proxy

Is responsible of making RMI transparent to clients by behaving like a local object to the invoker. The proxy implements (Java term, not literally) the methods in the interface of the remote object that it represents. But, Instead of executing an invocation, the proxy forwards it to a remote object. Each method of the proxy marshals the following into a request message: (i) a reference to the target object, (ii) its own method id and (iii) the argument values. Request message is sent to the target, then proxy awaits the reply message, un-marshals it and returns the results to the invoker.

Stubs and Skeletons


Stub Proxy on client side pretends to be remote object Marshall the parameter Skeleton Proxy on server receives requests from stub (Unmarshall the parameter) talks to true remote object delivers response to stub (Marshall return method)

Remote Interfaces and Stubs


Remote Interface

implements

implements

Client

Stub

Skeleton

Remote Object (Server)

Remote Reference Layer


Figures

out which remote object is being referenced Could span multiple virtual machines Communicates via TCP/IP

Transport Layer
Deals

with communications Connection management Dispatching messages between stub and skeleton Distributed Garbage Collection Sits on top of java.net

RMI Architecture

RMI Architecture

The first layer is the Stub/Skeleton Layer. This layer is responsible for managing the remote object interface between the client and server. The second layer is the Remote Reference Layer (RRL). This layer is responsible for managing the "liveliness" of the remote objects. It also manages the communication between the client/server and virtual machines, (e.g., threading, garbage collection, etc.) for remote objects. The third layer is the Transport Layer. This is the actual network/communication layer that is used to send the information between the client and server over the wire. It is currently TCP/IP based.

How RMI Works


RMI

uses a network-based registry to keep track of the distributed objects. The server object makes a method available for remote invocation by binding it to a name in the registry. The client object, in turn, can check for availability of an object by looking up its name in the registry . The registry acts as a limited central management point for RMI . The registry is simply a name repository . It does not address the problem of actually invoking the remote method.

How RMI Works


The

two objects may physically reside on different machines. A mechanism is needed to transmit the client's request to invoke a method on the server object to the server object and provide a response. RMI uses an approach similar to RPC in this regard. The code for the server object must be processed by an RMI compiler called rmic, which is part of the JDK.

How RMI Works


The

rmic compiler generates two files: a stub and a skeleton. The stub resides on the client machine and the skeleton resides on the server machine. The stub and skeleton are comprised of Java code that provides the necessary link between the two objects.

How RMI Works


When

a client invokes a server method, the JVM looks at the stub to do type checking (since the class defined within the stub is an image of the server class). The request is then routed to the skeleton on the server, which in turn calls the appropriate method on the server object. In other words, the stub acts as a proxy to the skeleton and the skeleton is a proxy to the actual remote method.

RMI System Working


Client Virtual Machine Client Server Virtual Machine Remote Object

Stub

Skeleton Server

Fred Registry Virtual Machine

RMI Flow
1. Server Creates Remote Object Client Virtual Machine 2. Server Registers Remote Object Client Server Virtual Machine Remote Object
1

Stub

Skeleton Server
2

Fred Registry Virtual Machine

RMI Flow
Client Virtual Machine Client Server Virtual Machine Remote 3. Client requests object from Registry Object 4. Registry returns remote reference (and stub gets created) Stub
3 4

Skeleton Server

Fred Registry Virtual Machine

RMI Flow
Client Virtual Machine Client
5 6 7

Server Virtual Machine Remote Object

Stub

Skeleton Server

5. Client invokes stub method 6. Stub talks to skeleton 7. Skeleton invokes remote object Fred method Registry Virtual Machine

Part II: RMI Usage

Overview of RMI Programming


Define an interface that declares the methods that will be available remotely. The server program must include a class that implements this interface. The server program must create a remote object and register it with the naming service.
The client program creates a remote object by asking the naming service for an object reference.

Steps
Create

source file and compile it Generate Stubs and Skeletons Install Files on the Client and Server Machines Start the RMI Registry on the Server Machine Start the Server Start the Client

Creating Remote Objects


Define
Define

a Remote Interface
java.rmi.Remote

extends

a class that implements the Remote Interface


extends

java.rmi.RemoteObject or java.rmi.UnicastRemoteObject

Remote Interface Example


import java.rmi.*; public interface AddServerIntf extends Remote { double add(double d1, double d2) throws RemoteException; }

Remote Class Example


import java.rmi.*; import java.rmi.server.*; public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf { public AddServerImpl() throws RemoteException { } public double add(double d1, double d2) throws RemoteException { return d1 + d2; } }

Remote Interfaces vs. Remote Classes


Remember

that the reference is to an

interface You must make references, arrays, etc. out of the interface type, not the implementation type You cant cast the remote reference to a normal reference So name your Remote Objects with Impl (so you dont get confused)

Parameter Passing
Primitive
passed

types

by value

Remote
passed

objects
by reference

Non-remote
passed

objects

by value uses Java Object Serialization

Create the server


Creates

a new instance of the remote object Registers it in the registry with a unique name Use Naming.bind or Naming.rebind method Bind throws AlreadBoundException if previous binding is there.

Server
import java.net.*; import java.rmi.*; public class AddServer { public static void main(String args[]) { try { AddServerImpl addServerImpl = new AddServerImpl(); Naming.rebind("AddServer", addServerImpl); } catch(Exception e) { System.out.println("Exception: " + e); } } }

Creating an RMI Client


Install
to

a Security Manager

protect from malicious stubs

Find

a registry
java.rmi.Naming

use

Lookup

the name, returns a reference Cast the reference to the appropriate Remote Interface

RMI URLs
rmi://host[:port]/name
default

port is 1099 Specifies hostname of registry can also use relative URLs
name

only assumes registry is on local host

RMI Client Example


import java.rmi.*; public class AddClient { public static void main(String args[]) { try { String addServerURL = "rmi://" + args[0] + "/AddServer"; AddServerIntf addServerIntf = (AddServerIntf)Naming.lookup(addServerURL); System.out.println("The first number is: " + args[1]); double d1 = Double.valueOf(args[1]).doubleValue(); System.out.println("The second number is: " + args[2]); double d2 = Double.valueOf(args[2]).doubleValue(); System.out.println("The sum is: " + addServerIntf.add(d1, d2)); } catch(Exception e) { System.out.println("Exception: " + e); } } }

Compiling classes
Compile
javac

the Java class

reads .java file produces .class file

Compile

the Server file Compile the Stub and Skeleton


rmic

reads .class file produces _Skel.class and _Stub.class

Compiling Remote Classes (Diagram)


AddServerImpl_Skel.class (skeleton classfile)

javac
AddServerImpl.java (remote class) AddServerImpl.class (classfile)

rmic

AddServerImpl_Stub.class (stub classfile)

Step 3
Make

Server folder

Copy

AddServerIntf.class, AddServerImpl.class, AddServerImpl_skel.class and AddServer.class

Make

Client folder

Copy

AddserverIntf.class, AddserverImpl_stub.class, AddClient.class

Registry CLASSPATH
Registry

VM needs to be able to find stub

file(s) You must set the CLASSPATH to include the directory containing the stub file Or, your server needs to specify the java.rmi.server.codebase System property (more later)

Registering Remote Classes


start

the registry

running

process Before running registry make sure the classpath is set properly
Unix:

rmiregistry &
Windows:

start rmiregistry For our example C:\server>set classpath=c:\server;c:\client C:\server>start rmiregistry C:\server>java AddServer

Launch the Server


Java AddServer

Start client
Java AddClient localhost 4 5

Output
C:\client>java -classpath . AddClient 127.0.0.1 5 7 The first number is: 5 The second number is: 7 The sum is: 12.0

Example2 RMI and Applet


A

applet is run on client side and it gets the message from the server

Interface class
import java.rmi.*; public interface Hello extends Remote { String sayHello() throws java.rmi.RemoteException; }

Server class
import java.rmi.server.*; import java.rmi.*; public class HelloImpl extends UnicastRemoteObject implements Hello { private String name; public HelloImpl(String s) throws RemoteException { super(); name = s; } public String sayHello() throws RemoteException { return "Hello World!"; }

Server class (continue)


public static void main(String args[]) {
try { HelloImpl obj = new HelloImpl("HelloServer"); Naming.rebind("HelloServer", obj); System.out.println("HelloServer bound in registry"); } catch (Exception e) { System.out.println("HelloImpl err: " + e.getMessage()); e.printStackTrace(); } } }

Applet class
import java.awt.*; import java.rmi.*; public class HelloApplet extends java.applet.Applet { String message = ""; public void init() { try { Hello obj = (Hello)Naming.lookup("//" + getCodeBase().getHost() + "/HelloServer"); message = obj.sayHello(); } catch (Exception e) { System.out.println("HelloApplet exception: " + e.getMessage()); e.printStackTrace(); } } public void paint(Graphics g) { g.drawString(message, 25, 50); } }

Html file to run applet


<HTML> <title>Hello World</title> <center> <h1>Hello World</h1> </center> The message from the HelloServer is: <p> <applet codebase="" code="HelloApplet" width=500 height=120> </applet> </HTML>

Output

RMI Security
Server

is untrusted Stubs could be changed rmic is OK, but someone could customcode an evil stub: its just a .class file

RMI Security Managers


AppletSecurityManager
stub

can only do what an applet can do

RMISecurityManager
disables

all functions except class definition and access A downloaded class is allowed to make a connection if the connection was initiated via the RMI transport.
None
Stub

loading disabled Stubs still work if they are in local classpath

Limitations of RMI
Java-only
but

you can use JNI on the server

Uses

TCP, not UDP At least two sockets per connection Untested for huge loads

RMI Vs RPC
Because

RPC is designed to be functional between all combinations of application language it requires that a call's data representation be converted from its local language into a common language in order for it to be transmitted across the network. RMI is designed to operate only within the java environment thus no changes to the call's data representation are required.

RMI Vs RPC
RMI

allows any Java object type to be used for communication-even if the client or server has never encountered it before. RPC require that only simple data types or defined structures be passed to and from the methods for remote execution. RMI also both client and server to dynamically load new object types as required RMI Language dependent RPC language neutral

Summary
RMI

is a very clean API Easy way to write distributed programs Wire protocol may need improvement for large-scale problems

You might also like