You are on page 1of 78

Distributed Systems Design

Distributed Objects and RMI


Slide set based on the text book and the one by Prof. M.L. Liu, California Polytechnic State University

COMP 6231, Fall 2007

Distributed Objects and RMI

Local versus Remote Procedure Call


Caller Caller Caller

Called

Stub Called Stub Transport Layer (e.g. TCP or UDP)

COMP 6231, Fall 2007

Distributed Objects and RMI

Steps of a Remote Procedure Call


1. 1 2. 3. 3 4. 5. 6. 7. 8. 9. 10. 10 Client Cli t procedure calls client stub in normal way d ll li t t b i l Client stub builds message, calls local OS Client s Client's OS sends message to remote OS Remote OS gives message to server stub Server stub unpacks parameters, calls server p p , Server does work, returns result to the stub Server stub packs it in message, calls local OS Server's OS sends message to client's OS Client's OS gives message to client stub Stub St b unpacks result, returns t client k lt t to li t
Distributed Objects and RMI 3

COMP 6231, Fall 2007

Remote and local method invocations


remote invocation A B C E invocation local invocation local invocation D local remote t invocation

Each process contains objects, some of which can receive remote invocations, others only local invocations Those that can receive remote invocations are called remote objects Objects need to know the remote object reference of an object in another process in order to invoke its methods. How do they get it? The remote interface specifies which methods can be invoked remotely
COMP 6231, Fall 2007 Distributed Objects and RMI 4

A remote object and its remote interface


remote object

remote interface { m1 m2 m3

Data m4 m5 m6

implementation of methods

COMP 6231, Fall 2007

Distributed Objects and RMI

The role of proxy and skeleton in remote method invocation


client object A proxy for B Request server remote skeleton object B & dispatcher for Bs class

Reply t servant Remote reference module

Communication Remote reference module module

Communication module

COMP 6231, Fall 2007

Distributed Objects and RMI

Role of client and server stub procedures in RPC


client process Request server process

client stub procedure client program Communication module

Reply

server stub procedure Communication dispatcher module service procedure

COMP 6231, Fall 2007

Distributed Objects and RMI

Stubs
Creating code for marshalling and unmarshalling is tedious and error-prone. Code can be generated fully automatically from interface definition. Code is embedded in stubs for client and server. Client stub represents server for client, Server stub represents client for server. Stubs achieve type safety. Stubs also perform synchronization.
COMP 6231, Fall 2007 Distributed Objects and RMI 8

Synchronization
Goal: achieve similar synchronization to local method invocation Achieved by stubs:
Client stub sends request and waits until server finishes Server stub waits for requests and calls server when request arrives

COMP 6231, Fall 2007

Distributed Objects and RMI

Representation of a remote object reference


32 bits
IP address

32 bits
port number

32 bits
time

32 bits
object numberinterface of remote object

A remote object reference must be unique in the distributed system and over time. It should not be reused after the object is deleted. The first two fields locate the object unless migration or re-activation re activation in a new process can happen The fourth field identifies the object within the process its interface tells the receiver what methods it has (e.g. class Method) A remote object reference is created by a remote reference module when a reference is passed as argument or result to another process
It will be stored in the corresponding proxy It will be passed in request messages to identify the remote object whose method is to be invoked
COMP 6231, Fall 2007 Distributed Objects and RMI 10

The Java RMI Architecture


Directory service object client supports the interface with the application program object server

maps the platform-independent stub/skeleton layer to the platform-dependent transport layer; carries out remote reference protocols sets up, maintains, and shuts down connections; and carries out the transport protocol

stub remote reference layer transport layer

skeleton remote reference layer transport layer

logical d l i l data path h


COMP 6231, Fall 2007 Distributed Objects and RMI

physical data path

11

Algorithm for developing the server-side software


1. 1 2. 3. 4. Open a directory for all the files to be generated for this application application. Specify the remote-server interface in SomeInterface.java. Compile it until there is no more syntax error. Implement the interface in SomeImpl.java Compile it until there is p p j p no more syntax error. Use the RMI compiler rmic to process the implementation class and generate the stub file and skelton file for the remote object:

rmic i

SomeImpl S I l

5. 6.

The files generated can be found in the directory as SomeImpl_Skel.class and SomeImpl_Stub.class. Steps 3 and 4 must be repeated each time that a change is made to the interface implementation. Create the object server program SomeServer.java. Compile it until there is no more syntax error. Activate the object server

java
COMP 6231, Fall 2007

SomeServer
Distributed Objects and RMI 12

Algorithm for developing the client-side software


1. 2. Open a directory for all the files to be generated for this application. Obtain a copy of the remote interface class file. Alternatively, Alternatively obtain a copy of the source file for the remote interface, and compile it using javac to generate the interface class file. Obtain a copy of the stub file for the implementation of the interface: Develop the client program SomeClient java, and compile it SomeClient.java to generate the client class. java SomeClient
COMP 6231, Fall 2007 Distributed Objects and RMI 13

3.

4. 4 5.

SomeImpl_Stub.class.

Activate the client.

Placement of files for a RMI application


Object Client host Object Server host object server directory object client directory SomeInterface.class SomeInterface class SomeClient.class SomeImpl_Stub.class SomeImpl Stub.class SomeInterface.class SomeServer.class SomeServer class SomeImpl.class SomeImpl_Skel.class

COMP 6231, Fall 2007

Distributed Objects and RMI

14

The Naming class of Java RMIregistry


void rebind (String name, Remote obj)
This method is used by a server to register the identifier of a remote object by name.

void bi d (St i name, R id bind (String Remote obj) t bj)


This method can alternatively be used by a server to register a remote object by name, but if the name is already bound to a remote object reference an exception is thrown thrown.

void unbind (String name, Remote obj)


This method removes a binding.

Remote lookup(String name)


This method is used by clients to look up a remote object by name. A remote object reference is returned.

String [] list()
This method returns an array of Strings containing the names bound in the registry.
COMP 6231, Fall 2007 Distributed Objects and RMI 15

HelloInterface
// A simple RMI interface file - M. Liu import java.rmi.*; /** * This is a remote interface. */ public interface HelloInterface extends Remote { /** * This remote method returns a message. * param name - a String containing a name. * return a String message. message */ public String sayHello(String name) throws java rmi RemoteException; java.rmi.RemoteException; } //end interface
COMP 6231, Fall 2007 Distributed Objects and RMI 16

Implementation of HelloInterface
import java.rmi.*; import java.rmi.server.*; /* This class implements the remote interface HelloInterface. */ public class HelloImpl extends UnicastRemoteObject implements HelloInterface { public HelloImpl() throws RemoteException { super( ); } public String sayHello(String name) throws RemoteException { return "Hello, World!" + name; } } // end class
COMP 6231, Fall 2007 Distributed Objects and RMI 17

Hello Server
import java.rmi.*; import java.rmi.server.*; import java.rmi.registry.Registry; import java.rmi.registry.LocateRegistry; import java.net.*; import java.io.*; java.io. ; /* This class represents the object server for a distributed object of class Hello, which implements the remote interface HelloInterface. */ p public class HelloServer { public static void main(String args[]) { InputStreamReader is = new InputStreamReader(System.in); ( ); BufferedReader br = new BufferedReader(is); String portNum, registryURL;
COMP 6231, Fall 2007 Distributed Objects and RMI 18

Start Hello Server


try{ System.out.println("Enter the RMIregistry port number:"); portNum = (br.readLine()).trim(); int RMIPortNum = Integer.parseInt(portNum); Integer parseInt(portNum); startRegistry(RMIPortNum); HelloImpl exportedObj = new HelloImpl(); registryURL = "rmi://localhost:" + p g y // portNum + "/hello"; / ; Naming.rebind(registryURL, exportedObj); System.out.println("Hello Server ready."); }// end try catch (Exception re) { System.out.println("Exception in HelloServer.main: " + re); } // end catch } // end main } // end class
COMP 6231, Fall 2007 Distributed Objects and RMI 19

Hello Client
import ja a io * impo t java.io.*; import java.rmi.*; /* This class represents the object client for a distributed object of class Hello, which implements the remote interface HelloInterface. */ public class HelloClient { public static void main(String args[]) { try { int RMIPort; String hostName; InputStreamReader is = new InputStreamReader(System.in); BufferedReader br B ff dR d b = new BufferedReader(is); B ff dR d (i ) System.out.println("Enter the RMIRegistry host name:"); hostName = br.readLine(); y p ( g yp ); System.out.println("Enter the RMIregistry port number:"); String portNum = br.readLine(); RMIPort = Integer.parseInt(portNum);
COMP 6231, Fall 2007 Distributed Objects and RMI 20

Hello Client, Continued


String registryURL = "rmi://" + hostName+ ":" + portNum + "/hello"; // find the remote object and cast it to an interface object HelloInterface h = (HelloInterface)Naming.lookup(registryURL); System.out.println("Lookup System out println("Lookup completed " ); // invoke the remote method String message = h.sayHello("Donald Duck"); System.out.println("HelloClient: " + message); y p ( g ); } // end try catch (Exception e) { System.out.println("Exception in HelloClient: " + e); } } //end main }//end class

COMP 6231, Fall 2007

Distributed Objects and RMI

21

Starting a RMI registry


// This method starts a RMI registry on the local host, if it // does not already exists at the specified port number. private static void startRegistry(int RMIPortNum) throws RemoteException{ try { Registry registry = LocateRegistry.getRegistry(RMIPortNum); registry.list( ); // This call will throw an exception g y ( p // if the registry does not already exist } catch (RemoteException e) { // No valid registry at that port port. Registry registry = LocateRegistry.createRegistry(RMIPortNum); } } // end startRegistry

COMP 6231, Fall 2007

Distributed Objects and RMI

22

Listing the registered names


// This method lists the names registered with a Registry object private static void listRegistry(String registryURL) throws RemoteException, MalformedURLException { System.out.println("Registry " + registryURL + " contains: "); String [ ] names = Naming.list(registryURL); for (int i=0; i < names.length; i++) System.out.println(names[i]); S t t i tl ( [i]) } //end listRegistry

COMP 6231, Fall 2007

Distributed Objects and RMI

23

Comparison of the RMI and the socket APIs


The remote method invocation API is an efficient tool for building network applications. It can be used in lieu of the socket API in a network application. Some of the tradeoffs between the RMI API and the socket API are as follows:

The socket API is closely related to the operating system, and hence has less execution overhead. For applications which require high performance, this may be a consideration consideration. The RMI API provides the abstraction which eases the task of software development. Programs developed with a higher level of abstraction are more comprehensible and hence easier to debug.
Distributed Objects and RMI 24

COMP 6231, Fall 2007

Typical optimizations?
Compile the stub inline to put arguments directly into message Two versions of stub; if (at bind time) sender and destination found to have same data representations, use host-specific representation p p Use a special send, then receive system call (requires O/S extension) Optimize the O/S kernel path itself to eliminate copying treat RPC as the most important task the kernel will do
COMP 6231, Fall 2007 Distributed Objects and RMI 25

Fancy argument passing


RPC is transparent for simple calls with a small amount of data passed
Transparent in the sense that the interface to the Transparent procedure is unchanged But exceptions thrown will include new exceptions associated with network

What about complex structures, pointers, big arrays? These will be very costly, and perhaps impractical to pass as arguments Most implementations limit size, types of RPC arguments. Very general systems less limited but much more costly. costly
COMP 6231, Fall 2007 Distributed Objects and RMI 26

Instantiation of remote objects


L C remote invocation instantiateinstantiate M N remote invocation K

COMP 6231, Fall 2007

Distributed Objects and RMI

27

Multithreading the server


Three major options:
Single-threaded server: only does one thing at g g a time, uses send/receive system calls and blocks while waiting (iterative server) Multi-threaded server: internally concurrent concurrent, each request spawns a new thread to handle it (concurrent server) Upcalls: event dispatch loop does a procedure call for each incoming event, like for X11 or PC s PCs running Windows.
COMP 6231, Fall 2007 Distributed Objects and RMI 28

Single threading: drawbacks


Applications can deadlock if a request cycle forms: Im waiting for you and you send me a request, which I cant handle Much of system may be idle waiting for replies to pending requests Harder to implement RPC protocol itself (need to use a timer interrupt to trigger acks, i i i k retransmission, which is awkward)
COMP 6231, Fall 2007 Distributed Objects and RMI 29

Multithreading
Idea is to support internal concurrency as if each process was really multiple processes that share one address space Thread scheduler uses timer interrupts and context switching to mimic a physical i hi i i h i l multiprocessor using the smaller number of CPU s CPUs actually available

COMP 6231, Fall 2007

Distributed Objects and RMI

30

Multithreaded RPC
Each incoming request is handled by spawning a new thread Designer must implement appropriate mutual exclusion to guard against race conditions and other concurrency problems Ideally, server is more active because it can p process new requests while waiting for its q g own RPCs to complete on other pending requests
COMP 6231, Fall 2007 Distributed Objects and RMI 31

Negatives to multithreading
Users may have little experience with concurrency and will then make mistakes Concurrency bugs are very hard to find due to non nonreproducible scheduling orders Reentrancy can come as an undesired surprise Threads need stacks hence consumption of memory can be very high Deadlock remains a risk, now associated with concurrency control Stacks for threads must be finite and can overflow, corrupting the address space
COMP 6231, Fall 2007 Distributed Objects and RMI 32

Threads: Concept and Implementation


Process
Thread activations

Activation stacks (parameters, local variables) Heap (dynamic storage, objects, global variables) 'text' (program code) system-provided resources (sockets, windows, open files)
COMP 6231, Fall 2007 Distributed Objects and RMI 33

Threads versus multiple processes


Creating a thread is (much) cheaper than a process (~10-20 times) Switching to a different thread in same process is (much) cheaper (5-50 times) Threads within same process can share data and other resources more conveniently and efficiently ( ith t copying or messages) ffi i tl (without i ) Threads within a process are not protected from each other
COMP 6231, Fall 2007 Distributed Objects and RMI 34

Client and server with threads


Thread 2 makes requests to server Receipt & t t queuing Thread 1 generates results Input-output

Requests N threads Server

Client

The 'worker pool' architecture

COMP 6231, Fall 2007

Distributed Objects and RMI

35

Alternative server threading architectures


server process I/O /O workers server process per-connection threads remote objects server process per-object threads I/O remote objects remote t objects

a. Thread-per-request (a) (b) (c)

b. Thread-per-connection

c. Thread-per-object

Implemented by the server-side ORB in CORBA


Would be useful for UDP-based service, e.g. NTP is the most commonly used - matches the TCP connection model is used where the service is encapsulated as an object. Each object has only one thread, avoiding the need for thread synchronization within objects.
Distributed Objects and RMI 36

COMP 6231, Fall 2007

Support for communication and invocation


The performance of RPC and RMI mechanisms is critical for effective distributed systems. t
Typical times for 'null procedure call': Local procedure call < 1 microseconds Remote procedure call ~ 10 milliseconds 'network time' (involving about 100 bytes network time transferred, at 100 megabits/sec.) accounts for only .01 millisecond; the remaining delays must be in OS and middleware - latency not latency, communication time.
COMP 6231, Fall 2007 Distributed Objects and RMI 37

Support for communication and invocation


Factors affecting RPC/RMI performance
marshalling/unmarshalling + operation despatch at th server t the data copying: application -> kernel space -> communication buffers thread scheduling and context switching: including kernel entry protocol processing: for each protocol layer network access delays: connection setup, network latency
COMP 6231, Fall 2007 Distributed Objects and RMI 38

Implementation of invocation mechanisms


Most invocation middleware (Corba, Java RMI, HTTP) is implemented over TCP
For universal availability, unlimited message size and availability reliable transfer. Sun RPC (used in NFS) is implemented over both UDP and TCP and generally works faster over UDP

Research-based systems have implemented much more efficient invocation protocols. protocols Concurrent and asynchronous invocations
middleware or application doesn t block waiting for doesn't reply to each invocation
COMP 6231, Fall 2007 Distributed Objects and RMI 39

Java thread constructor and management methods


Thread(ThreadGroup group, Runnable target, String name) Creates a new thread in the SUSPENDED state, which will belong to group and be identified as name; the thread will execute the run() method of target. setPriority(int newPriority), getPriority()
Set and return the threads priority.

run()
A thread executes the run() method of its target object if it has one and object, one, otherwise its own run() method (Thread implements Runnable).

start()
Change the state of the thread from SUSPENDED to RUNNABLE.

sleep(int millisecs)
Cause the thread to enter the SUSPENDED state for the specified time.

yield()
Enter the READY state and invoke the scheduler.

destroy()
Destroy the thread.
COMP 6231, Fall 2007 Distributed Objects and RMI 40

Java thread synchronization calls


thread.join(int millisecs)
Blocks the calling thread for up to the specified time until thread has terminated terminated.

thread.interrupt() Interrupts thread: causes it to return from a blocking method call such as sleep(). object.wait(long millisecs, int nanosecs) Blocks the calling thread until a call made to notify() or notifyAll() on object wakes the thread or the thread is thread,
interrupted, or the specified time has elapsed.

object.notify(), object.notifyAll()
Wakes, respectively, Wakes respectively one or all of any threads that have called wait() on object.
COMP 6231, Fall 2007 Distributed Objects and RMI 41

Invocations between address spaces


(a) System call Thread Control transfer via trap instruction Control transfer via C t lt f i privileged instructions User Kernel Protection domain boundary

(b) RPC/RMI (within one computer)

Thread 1

Thread 2

User 1
COMP 6231, Fall 2007

Kernel

User 2
42

Distributed Objects and RMI

Invocations between address spaces


(c) RPC/RMI (between computers) Network

Thread 1

Thread 2

User 1 Kernel 1 Kernel 2

User 2

COMP 6231, Fall 2007

Distributed Objects and RMI

43

Upcall model
Common in windowing systems Each incoming event is encoded as a event small descriptive data structure User registers event handling procedures Dispatch loop calls the procedures as new events arrive, waits for the call to finish, then dispatches a new event
COMP 6231, Fall 2007 Distributed Objects and RMI 44

Upcalls combined with threads


Perhaps the best model for RPC programming Each handler can be tagged: needs thread, thread or can be executed unthreaded Developer must still be very careful where threads are used
COMP 6231, Fall 2007 Distributed Objects and RMI 45

Statefulness issues
Client-server system is stateless if:

Client is independently responsible for its actions, actions server doesnt track set of clients or ensure that cached data stays up to date.
The UNIX NFS file system is stateless. y

Client-server system is stateful if:

Server tracks its clients, takes actions to keep , p their cached states current. Client can trust its cached data.
Database systems are usually stateful stateful.
COMP 6231, Fall 2007 Distributed Objects and RMI 46

Stateful vs. Stateless server


A stateful server maintain stateful i f t t f l i t i t t f l information on each ti h active client. State information can reduce the data exchanged, and g , thereby the response time.
FTP se rve r FTP C l i e n t file fil ID fil posit ion file i i FTP se rve r FTP C l i e n t file ID file posit ion

GET file name file ID send <file ID>, block 0 data from block 0 of file send <file ID>, block 1 data from block 1 of file

GET file name ready send next block data from block 0 of file send next block data from block 1 of file

...
COMP 6231, Fall 2007 Distributed Objects and RMI

...
47

Stateful vs. Stateless server


Stateless server is straightforward to code. Stateful server is harder to code, but the , state information maintained by the server can reduce the data exchanged, and allows enhancements to a basic service. Maintaining state information is difficult in the presence of f il f failures

COMP 6231, Fall 2007

Distributed Objects and RMI

48

Typical issues in design


Client is generally simpler than server: may be single-threaded, can wait for reply to RPCs RPC s Server is generally multithreaded, designed to achieve extremely high concurrency and throughput. Much harder to develop p Reliability issue: if server goes down, all its clients may be stuck. Usually addressed with some form of backup or replication.
COMP 6231, Fall 2007 Distributed Objects and RMI 49

Performance: the monster in the closet


Often, the hidden but huge issue is that we want high performance
After all, a slow system costs more to operate and may drive users crazy!

The issue is that some techniques seem simple and seem to do the trick but are as much as thousands of times slower than other alternatives th lt ti
Forcing us to use those alternatives... And perhaps g y p pp driving us away from what the platforms support
COMP 6231, Fall 2007 Distributed Objects and RMI 50

Broad comments on RPC


RPC is not very transparent Failure handling is not evident at all: if an RPC times out, what should the developer do? ti t h t h ld th d l d ?
Reissuing the request only makes sense if there is another server available Anyhow, what if the request was finished but the reply was lost? Do it twice? Try to duplicate the lost reply?

Performance work is producing enormous gains: from the old 75ms RPC to RPC over U/Net with a 75usec round-trip time: a factor of 1000! 75 d t i ti f t f
COMP 6231, Fall 2007 Distributed Objects and RMI 51

RPC costs in case of local destination process


Often, the destination is right on the callers machine!
Caller builds message Issues send system call, blocks, context switch Message copied into kernel, then out to dest. Dest is blocked... wake it up, context switch Dest computes result Entire sequence repeated in reverse direction If scheduler is a process context switch 6 times! process,
COMP 6231, Fall 2007 Distributed Objects and RMI 52

Important optimizations: LRPC


Lightweight RPC (LRPC): for case of sender, destination on same machine (Bershad et. al.) l) Uses memory mapping to pass data Reuses same kernel thread to reduce context switching costs (user suspends and server wakes up on same kernel thread or stack) p ) Single system call: send_rcv or rcv_send

COMP 6231, Fall 2007

Distributed Objects and RMI

53

Bershad's LRPC
Uses shared memory for interprocess communication
while maintaining protection of the two processes arguments copied only once (versus four times g p y ( for convenitional RPC)

Client threads can execute server code


via protected entry points only ( i t t d t i t l (uses capabilities)

Up to 3 x faster for local invocations


COMP 6231, Fall 2007 Distributed Objects and RMI 54

A lightweight remote procedure call


Client Server

A stack
1. Copy args

A
4. Execute procedure and copy results

User Kernel

stub t b

stub t b

2. Trap to Kernel

3. Upcall

5. Return (trap)

COMP 6231, Fall 2007

Distributed Objects and RMI

55

LRPC performance impact


On same platform, offers about a 10-fold improvement over a hand-optimized RPC implementation i l t ti Does two memory remappings, no context switch Runs about 50 times faster than standard RPC by same vendor ( the time of the y (at research) Semantics stronger: easy to ensure exactly once
COMP 6231, Fall 2007 Distributed Objects and RMI 56

Times for serialized and concurrent invocations


Serialised invocations process args marshal Send process args marshal Send process args marshal Se d Send Concurrent invocations transmission Receive unmarshal execute request marshal Send Receive unmarshal process results process args marshal Send Receive R i unmarshal execute request marshal Send Receive unmarshal process results Client COMP 6231, Fall 2007 Server Client Distributed Objects and RMI Server 57 Receive ece e unmarshal execute request marshal Send Receive unmarshal execute request marshal Send

Receive unmarshal process results Receive unmarshal process results

time

Callback
In h li I the client server model, the server is passive: the d l h i i h IPC is initiated by the client; the server waits for the q p p arrival of requests and provides responses. Some applications require the server to initiate communication upon certain events. Examples applications are:
monitoring games auctioning voting/polling chat-room message/bulletin board groupware

COMP 6231, Fall 2007

Distributed Objects and RMI

58

Polling vs. Callback


In h b I the absence of callback, a client will have to poll a f llb k li ill h ll passive server repeatedly if it needs to be notified that an event has occurred at the server end.
Polling
Server

Callback
Server

...
Client A client issues a request to the server repeatedly until the desired response is obtained.
COMP 6231, Fall 2007

Client A client registers itself with the server, and wait until the server calls back.

a remote method call Distributed Objects and RMI

59

Two-way communications
Some applications require that both sides may initiate IPC. Using sockets, duplex communication can be achieved by using two sockets on either side. With connection-oriented sockets, each side acts as both a client and a server.
Process 1 request response request response Process 1

COMP 6231, Fall 2007

Distributed Objects and RMI

60

RMI Callbacks
A callback client registers itself with an RMI server. The server makes a callback to each registered client upon the occurrence of a certain event.
Server Clients C1 The callback list C2 RMI calls callback C4

C3

C5

COMP 6231, Fall 2007

Distributed Objects and RMI

61

Callback Client-Server Interactions


Client host 1 2 Server host Client.class RMI registry SomeInterface_stub.class 3,4
X

SomeInterface_skel.class SomeServer.class S S l

CallbackInterface_skel.class 5

CallbackInterface_stub.class 1. Cli t l k 1 Client looks up the interface object in the RMI i t on th server h t th i t f bj t i th RMIregistry the host. 2. The RMIRegistry returns a remote reference to the interface object. 3. Via the server stub, the client process invokes a remote method to register itself for callback, passing a remote reference to itself to the server. The server saves the reference in its callback list. 4. Via the server stub, the client process interacts with the skeleton of the interface object to access the methods in the interface object. 5. When the anticipated event takes place, the server makes a callback to each registered client via the callback interface stub on the server side and the callback interface skeleton on the client side. COMP 6231, Fall 2007 Distributed Objects and RMI

62

Callback application files


Object client host object client directory Client.class
ClientInterface.class S erverInterface.class

Object server host object server directory Server.class


S erverInterface.class ClientInterface.class

ClientImpl.class
S erverImpl_S tub.class ClientImpl_skel.class

ServerImpl.class
ClientImpl_S tub.class S erverImpl_skel.class

COMP 6231, Fall 2007

Distributed Objects and RMI

63

RMI Callback file placements


Client host client directory SomeClient.class CallbackInterface_skel.class java.policy Server host server directory SomeServer.class SomeInterface_stub.class SomeInterface.Skeleton.class CallbackInterface_stub.class CallbackInterface stub class

java.polcy HTTP Server SomeInterface_stub.class

COMP 6231, Fall 2007

Distributed Objects and RMI

64

RMI Callback Interface


The server provides a remote method which allows a client to register itself for callbacks. A Remote interface for the callback is needed, in addition to the server-side interface. The interface specifies a method for accepting a callback from the server server. The client program is a subclass of RemoteObject and implements the callback interface, including the callback method. The client registers itself for callback in its main method. The server invokes the clients remote method upon the client s occurrence of the anticipated event.
COMP 6231, Fall 2007 Distributed Objects and RMI 65

Callback Client Interface


import java.rmi.*; /** * This is a remote interface for illustrating RMI client callback. * @author M L Liu */ M. L. public interface CallbackClientInterface extends java.rmi.Remote { // This remote method is invoked by a callback y // server to make a callback to an client which // implements this interface. // @param message - a string containing information for the // client to process upon being called back back. public String notifyMe(String message) throws java.rmi.RemoteException; } // end interface
COMP 6231, Fall 2007 Distributed Objects and RMI 66

Callback Client Implementation


import java.rmi.*; import java.rmi.server.*; /** This class implements the remote interface CallbackClientInterface. * @author M. L. Liu */ M L public class CallbackClientImpl extends UnicastRemoteObject implements CallbackClientInterface { p public CallbackClientImpl() throws RemoteException { super( ); } public String notifyMe(String message){ String returnMessage = "Call back received: " + message; System.out.println(returnMessage); return returnMessage; } }// end CallbackClientImpl class
COMP 6231, Fall 2007 Distributed Objects and RMI 67

Callback Client
import java.io.*; import java.rmi.*; /** This class represents the object client for a distributed object of class * CallbackServerImpl, which implements the remote interface CallbackServerImpl * CallbackServerInterface. It also accepts callback from the server. */ p public class CallbackClient { public static void main(String args[]) { try { int RMIPort; String hostName; InputStreamReader is = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(is); System.out.println( "Enter the RMIRegistry host namer:"); hostName = br.readLine();
COMP 6231, Fall 2007 Distributed Objects and RMI 68

Callback Client, Continued


System.out.println("Enter the RMIregistry port number:"); String portNum = br.readLine(); RMIPort = Integer.parseInt(portNum); System.out.println("Enter System out println("Enter how many seconds to stay registered:"); String timeDuration = br.readLine(); int time = Integer.parseInt(timeDuration); String registryURL = "rmi://localhost:" + p g g y // portNum + "/callback"; / ; // find the remote object and cast it to an interface object CallbackServerInterface h = (CallbackServerInterface)Naming.lookup(registryURL); System.out.println( Lookup System out println("Lookup completed " ); System.out.println("Server said " + h.sayHello()); CallbackClientInterface callbackObj = new CallbackClientImpl();

COMP 6231, Fall 2007

Distributed Objects and RMI

69

Callback Client, Continued


// register for callback h.registerForCallback(callbackObj); System.out.println("Registered for callback."); try { Thread.sleep(time * 1000); } catch (InterruptedException ex){ // sleep over ( p p ){ p } h.unregisterForCallback(callbackObj); System.out.println("Unregistered for callback."); } // end try catch (Exception e) { System.out.println("Exception in CallbackClient: " + e); } // end catch } //end main }//end class
COMP 6231, Fall 2007 Distributed Objects and RMI 70

Callback Server Interface


import java.rmi.*; /** * This is a remote interface for illustrating RMI client callback. */ public interface CallbackServerInterface extends Remote { public String sayHello( ) throws java rmi RemoteException; java.rmi.RemoteException; // This remote method allows an object client to register for callback // @param callbackClientObject is a reference to the object of the // client; to be used by the server to make its callbacks. ; y public void registerForCallback( CallbackClientInterface callbackClientObject ) throws java.rmi.RemoteException; // This remote method allows an object client to // cancel its registration for callback public void unregisterForCallback( CallbackClientInterface callbackClientObject) throws java.rmi.RemoteException;}
COMP 6231, Fall 2007 Distributed Objects and RMI 71

Callback Server Implementation


import java.rmi.*; import java.rmi.server.*; import java.util.Vector; /** This class implements the remote interface CallbackServerInterface. * @author M. L. Liu */ public class CallbackServerImpl extends UnicastRemoteObject implements CallbackServerInterface { private Vector clientList; public CallbackServerImpl() throws RemoteException { super( ); clientList = new Vector(); }
COMP 6231, Fall 2007 Distributed Objects and RMI 72

Callback Server Implementation, Continued


public String sayHello( ) throws java.rmi.RemoteException { return("hello"); } public synchronized void registerForCallback( CallbackClientInterface callbackClientObject) j ) throws java.rmi.RemoteException{ // store the callback object into the vector if (!(clientList.contains(callbackClientObject))) { clientList.addElement(callbackClientObject); clientList addElement(callbackClientObject); System.out.println("Registered new client "); doCallbacks(); } // end if }
COMP 6231, Fall 2007 Distributed Objects and RMI 73

Callback Server Implementation, Continued


// This remote method allows an object client to // cancel its registration for callback // @param id is an ID for the client; to be used by // the server to uniquely identify the registered client client. public synchronized void unregisterForCallback( CallbackClientInterface callbackClientObject) throws java.rmi.RemoteException{ j p { if (clientList.removeElement(callbackClientObject)) { System.out.println("Unregistered client "); } else { System.out.println( System out println( "unregister: clientwasn't registered."); } }

COMP 6231, Fall 2007

Distributed Objects and RMI

74

Callback Server Implementation, Continued


private synchronized void doCallbacks( ) throws java.rmi.RemoteException{ // make callback to each registered client for (int i = 0; i < clientList.size(); i++){ clientList size(); System.out.println("doing "+ i +"-th callback\n"); // convert the vector object to a callback object CallbackClientInterface nextClient = (CallbackClientInterface)clientList.elementAt(i); // invoke the callback method nextClient.notifyMe("Number of registered clients="+ clientList.size()); }// end for } // doCallbacks }// end C llb kS d CallbackServerImpl class I l l
COMP 6231, Fall 2007 Distributed Objects and RMI 75

Callback Server
import java.rmi.*; import java.rmi.server.*; import java.rmi.registry.Registry; import java rmi registry LocateRegistry; java.rmi.registry.LocateRegistry; import java.net.*; import java.io.*; / /** * This class represents the object server for a distributed object of p j j class Callback, which implements the remote interface CallbackInterface. @author M. L. Liu */ public class CallbackServer { public static void main(String args[]) { InputStreamReader is = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(is); String portNum, registryURL;

COMP 6231, Fall 2007

Distributed Objects and RMI

76

Callback Server, Continued


try{ System.out.println( "Enter the RMIregistry port number:"); portNum = (br.readLine()).trim(); int RMIPortNum = Integer.parseInt(portNum); Integer parseInt(portNum); startRegistry(RMIPortNum); CallbackServerImpl exportedObj = new CallbackServerImpl(); registryURL = "rmi://localhost:" + p g y // portNum + "/callback"; / ; Naming.rebind(registryURL, exportedObj); System.out.println("Callback Server ready."); }// end try catch (Exception re) { System.out.println("Exception in HelloServer.main: " + re); } // end catch } // end main

COMP 6231, Fall 2007

Distributed Objects and RMI

77

Callback Server, Continued


//This method starts a RMI registry on the local host, if //it does not already exists at the specified port number. private static void startRegistry(int RMIPortNum) throws RemoteException{ try { Registry registry = LocateRegistry.getRegistry(RMIPortNum); registry.list( ); g y ( // This call will throw an exception // if the registry does not already exist } catch (RemoteException e) { // No valid registry at that port port. Registry registry = LocateRegistry.createRegistry(RMIPortNum); } } // end startRegistry } // end class
COMP 6231, Fall 2007 Distributed Objects and RMI 78

You might also like