java rmi tutorial

Embed Size (px)

Citation preview

  • 7/30/2019 java rmi tutorial

    1/18

    JavaTMRMI Tutorial

    Revision 1.3JDK 1.1 FCS, February 10, 1997

  • 7/30/2019 java rmi tutorial

    2/18

    Copyright 1996, 1997 Sun Microsystems, Inc.2550 Garcia Avenue, Mountain View, California 94043-1100 U.S.A.All rights reserved. Copyright in this document is owned by Sun Microsystems, Inc.

    Sun Microsystems, Inc. (SUN) hereby grants to you a fully-paid, nonexclusive, nontransferable, perpetual,worldwide limited license (without the right to sublicense) under SUN's intellectual property rights that areessential to practice this specification. This license allows and is limited to the creation and distribution of cleanroom implementations of this specification that (i) include a complete implementation of the current version ofthis specification without subsetting or supersetting, (ii) implement all the interfaces and functionality of thestandard java.* packages as defined by SUN, without subsetting or supersetting, (iii) do not add any additionalpackages, classes or methods to the java.* packages (iv) pass all test suites relating to the most recent publishedversion of this specification that are available from SUN six (6) months prior to any beta release of the cleanroom implementation or upgrade thereto, (v) do not derive from SUN source code or binary materials, and (vi)do not include any SUN binary materials without an appropriate and separate license from SUN.

    RESTRICTED RIGHTS LEGEND

    Use, duplication, or disclosure by the U.S. Government is subject to restrictions of FAR 52.227-14(g)(2)(6/87)and FAR 52.227-19(6/87), or DFAR 252.227-7015(b)(6/95) and DFAR 227.7202-1(a).

    TRADEMARKS

    Sun, the Sun logo, Sun Microsystems, JavaBeans, JDK, Java, HotJava, the Java Coffee Cup logo, Java Work-Shop, Visual Java, Solaris, NEO, Joe, Netra, NFS, ONC, ONC+, OpenWindows, PC-NFS, SNM, SunNet Man-

    ager, Solaris sunburst design, Solstice, SunCore, SolarNet, SunWeb, Sun Workstation, The Network Is TheComputer, ToolTalk, Ultra, Ultracomputing, Ultraserver, Where The Network Is Going, Sun WorkShop,XView, Java WorkShop, the Java Coffee Cup logo, and Visual Java are trademarks or registered trademarks ofSun Microsystems, Inc. in the United States and other countries.

    UNIX is a registered trademark in the United States and other countries, exclusively licensed throughX/Open Company, Ltd. OPEN LOOK is a registered trademark of Novell, Inc.

    All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC Interna-tional, Inc. in the United States and other countries. Products bearing SPARC trademarks are based upon an

    architecture developed by Sun Microsystems, Inc.

    THIS PUBLICATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHEREXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.

    THIS PUBLICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICALERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN; THESECHANGES WILL BE INCORPORATED IN NEW EDITIONS OF THE PUBLICATION. SUN MICROSYS-TEMS, INC. MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THEPROGRAM(S) DESCRIBED IN THIS PUBLICATION AT ANY TIME.

    For further information on Intellectual Property matters contact Sun Legal Department:

    Trademarks, Jan O'Dell at 415-786-8191Patents at 415-336-0069

  • 7/30/2019 java rmi tutorial

    3/18

    Page iii

    Table of Contents

    1 Getting Started Using RMI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

    1.1 Write The HTML and Java Source Files. . . . . . . . . . . . . . . 1

    1.1.1 Define a Remote Interface . . . . . . . . . . . . . . . . . . . . . 2

    1.1.2 Write an Implementation Class . . . . . . . . . . . . . . . . . 3

    1.1.3 Write an Apple t tha t Uses the Remote Serv ice . . . . 8

    1.1.4 Write the Web Page that Contains the Applet . . . . . 9

    1.2 Compile and Deploy Class Files and HTML Files . . . . . . 9

    1.2.1 Compile the Java Source Files . . . . . . . . . . . . . . . . . . 10

    1.2.2 Generate Stubs and Skeletons. . . . . . . . . . . . . . . . . . 101.2.3 Move the HTML File to the Deployment Directory 11

    1.2.4 Set Paths for Runtime . . . . . . . . . . . . . . . . . . . . . . . . . 11

    1.3 Start the Remote Object Registry, Server, and Applet . . . 11

    1.3.1 Start the RMI Bootstrap Registry . . . . . . . . . . . . . . . 11

    1.3.2 Start the Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

    1.3.3 Run the Applet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

  • 7/30/2019 java rmi tutorial

    4/18

    Page iv Java RM I TutorialJDK 1.1 FCS, February10, 1997

  • 7/30/2019 java rmi tutorial

    5/18

    Page 1

    Getting Started Using RM I1

    This chapter shows you the steps to follow to create a distributed version of

    the classic Hello World p rogram using Java Remote Method Invocation

    (RMI).

    The distributed Hello World example uses an applet to make a remote method

    call to the server from wh ich it was d own loaded to retrieve the message H ello

    World!. When the applet runs, the message is displayed on the client.

    To accomp lish this, you will work th rough the follow ing three lessons:

    Write The HTML and Java Source Files

    Comp ile and Dep loy Class Files and HTML Files

    Start the Remote Object Registry, Server, and Applet

    1.1 Write The HTML and Java Source Files

    There are four source files for the H ello World server a nd app let:

    1. The Java remote interface.

    2. The Java remote object (server) which implements the rem ote interface.

    3. The Java app let that remotely invokes the servers method.

    4. The HTML code for the web p age that references the app let.

  • 7/30/2019 java rmi tutorial

    6/18

    Page 2 Java RM I TutorialJDK 1.1 FCS, February 10, 1997

    1

    Because the Java language requires a mapping between the fully qualified

    package na me of a class file and the d irectory p ath to th at class, before you

    begin writing Java code you need to decide on package and directory names.

    (This map ping allows the Java comp iler to know the d irectory in wh ich to find

    the class files mentioned in a Java p rogram.) For the H ello World p rogram

    developed in this chapter, the package name is examples.hello and th e root

    directory is $HOME/java/mysrc/examples/hello .

    For example, to create the d irectory for you r sou rce files on Solaris, execute this

    command:

    mkdir $HOME/java/mysrc/examples/hello

    1.1.1 Define a Remote Interface

    Remote method invocations can fail in very different w ays from local method

    invocations, due to network related communication problems and server

    problems. To ind icate that it is a remote object, an object implemen ts a remote

    interface, w hich h as th e following characteristics:

    The remote interface must be p ublic. Otherw ise, a client w ill get an error

    when attempting to load a remote object that implements the remoteinterface.

    The remote interface extends the interface java.rmi.Remote.

    Each m ethod m ust d eclare java.rmi.RemoteException in its throws

    clause, in add ition to an y ap plication-specific exceptions.

    A remote object passed as an argument or return value (either directly or

    embed ded within a local object) mu st be declared as the rem ote interface,

    not the implementation class.

    Here is th e interface d efinition for H ello World. The interface contains just one

    method, sayHello, which returns a string to the caller:

    package examples.hello;

    public interface Hello extends java.rmi.Remote {

    String sayHello() throws java.rmi.RemoteException;

    }

  • 7/30/2019 java rmi tutorial

    7/18

    Getting Started Using RMI Page 3

    1

    1.1.2 Write an Implementation Class

    To w rite a remote object, you wr ite a class that imp lements one or m ore remote

    interfaces. The implemen tation class needs to:

    1. Specify the remote interface(s) being implemented .

    2. Define the constructor for the remote object.

    3. Provide imp lementations for the method s that can be invoked remotely.

    4. Create and install a security manager.

    5. Create one or more instances of a remote object.

    6. Register at least one of the remote objects with th e RMI remote object

    registry, for bootstrapping purposes.

    For example, here is the sou rce for the HelloImpl.java file, which contains

    the code for th e H ello World server. The code is followed by an explanation of

    each of the p receding six steps.

    package examples.hello;

    import java.rmi.*;

    import java.rmi.server.UnicastRemoteObject;

    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!";

    }

  • 7/30/2019 java rmi tutorial

    8/18

    Page 4 Java RM I TutorialJDK 1.1 FCS, February 10, 1997

    1

    public static void main(String args[])

    {

    // Create and install a security manager

    System.setSecurityManager(new RMISecurityManager());

    try {

    HelloImpl obj = new HelloImpl("HelloServer");

    Naming.rebind("//myhost/HelloServer", obj);

    System.out.println("HelloServer bound in registry");

    } catch (Exception e) {

    System.out.println("HelloImpl err: " + e.getMessage());

    e.printStackTrace();

    }

    }}

    w Im p l e m e n t a Re m o t e I n te r fa c e

    The implemen tation class for the Hello World exam ple is HelloImpl. An

    implemen tation class specifies the remote interface(s) it is implementing.

    Optionally, it can indicate the remote server that it is extend ing, wh ich in this

    example is java.rmi.server.UnicastRemoteObject . Here is the

    HelloImpl class declaration:

    public class HelloImpl

    implements Hello

    extends java.rmi.server.UnicastRemoteObject

    Extending UnicastRemoteObject indicates that the HelloImpl class is used

    to create a single (nonreplicated) remote object that uses RMIs default sockets-

    based tra nspor t for commu nication. If you choose to extend a rem ote object

    from a n onremote class, you n eed to explicitly export the rem ote object by

    calling th e method UnicastRemoteObject.exportObject .

  • 7/30/2019 java rmi tutorial

    9/18

    Getting Started Using RMI Page 5

    1

    w D e fi n e th e C o n stru c to r fo r th e Re m o t e O b j e c t

    The constructor for a remote class is no d ifferent th an th e constructor for a

    nonrem ote class: it initializes the variables of each new ly created instance ofthe class.

    Here is the constructor for the HelloImpl class, wh ich initializes th e p rivate

    string variable name with the name of the remote object:

    private String name;

    public HelloImpl(String s) throws java.rmi.RemoteException {

    super();

    name = s;

    }

    Note the following:

    The super method call invokes the no-arg constructor of

    java.rmi.server.UnicastRemoteObject , which exports the remote

    object by listening for incoming calls to the remote object on a n an onym ous

    port.

    The constructor must throw java.rmi.RemoteException, becau se RMIs

    attempt to export a remote object during construction might fail ifcommu nication resou rces are not available.

    Although the call to the super no-arg constructor occurs b y d efault if omitted,

    it is included in this example to m ake clear the fact that Java constructs the

    superclass before the class.

    w P r o v i d e a n I m p l e m e n t a t i o n f o r E a c h R e m o t e M e t h o d

    The implemen tation class for a remote object contains the cod e thatimplements each of the remote methods specified in the remote interface.

    For example, here is the implementation for the sayHello method, w hich

    returns the string Hello World! to the caller.

    public String sayHello() throws RemoteException {

    return "Hello World!";

    }

  • 7/30/2019 java rmi tutorial

    10/18

    Page 6 Java RM I TutorialJDK 1.1 FCS, February 10, 1997

    1

    Arguments to, or return values from, remote methods can be of any Java type,

    includ ing objects, as long a s those ob jects imp lement th e interface

    java.io.Serializable. Most of the core Java classes in java.lang an d

    java.util implement the Serializable interface.

    Local objects are passed by copy, and on ly the non static and nontr ansient

    fields are copied by default.

    Remote objects are passed by reference. A reference to a remote object is

    actually a reference to a stu b, wh ich is a client-side p roxy for the remote

    object. Stubs are described fully in Section 1.2.2, Generate Stubs and

    Skeletons.

    Note A class can define methods not specified in the remote interface, but

    those methods can only be invoked w ithin the virtual machine run ning the

    service and cannot be invok ed rem otely.

    w C r e a te a n d I n sta ll a Se c u rity M a n a g e r

    The main method of the service first need s to create and install a security

    manager: either the RMISecurityManager or one that you have d efinedyourself. For example:

    System.setSecurityManager(new RMISecurityManager());

    A security manager n eeds to be run ning so that it can guarantee that the

    classes load ed d o not p erform sensitive operations. If no security m anager is

    specified, no class loading for RMI classes, local or otherwise, is allowed.

    w C r e a te O n e o r M o re I n sta n c e s o f a Re m o t e O b j e c t

    The main method of the service needs to create one or more instances of the

    remote object w hich provid es the service. For examp le:

    HelloImpl obj = new HelloImpl("HelloServer");

    The constructor exports the rem ote object, wh ich m eans that once created, the

    remote object is ready to begin listening for incoming calls.

  • 7/30/2019 java rmi tutorial

    11/18

    Getting Started Using RMI Page 7

    1

    w Re g iste r a Re m o t e O b j e c t

    For a caller (client, peer, or app let) to be able to invoke a m ethod on a rem ote

    object, that caller must first obtain a reference to the remote object. Most of thetime, the reference will be obtained as a parameter to, or a return value from,

    another remote method call.

    For bootstrapp ing, the RMI system also p rovides a URL-based registry tha t

    allows you to bind a URL of the form //host/objectname to the remote

    object, where objectname is a simple string n ame. On ce a remote object is

    registered on the server, callers can look up the object by na me, obtain a rem ote

    object reference, and th en rem otely invoke m ethod s on th e object.

    For example, the following code bind s the URL of the remote object named

    HelloServer to a reference for the remote object:

    Naming.rebind("//myhost/HelloServer", obj);

    Note the following about the arguments to the call:

    The host defaults to the current host if omitted from the URL, and no

    protocol needs to be sp ecified in the URL.

    The RMI runtime substitutes a reference to the rem ote objects stub for theactual remote object reference specified by th e obj argument. Remote

    implem entation ob jects like instan ces ofHelloImpl never leave the virtual

    machine where they are created, so when a client performs a lookup in a

    server s remote object registry, a reference to the stu b is retur ned .

    Optionally, a port number can be supplied in the URL: for example

    / / myh ost:1234/ HelloServer. The por t defaults to 1099. It is necessar y to

    specify the port number only if a server creates a registry on a port other

    than the d efault 1099.

    Note For security reasons, an application can bind or unbind only in the

    registry running on the same host. This prevents a client from removing or

    overw riting any of the entries in a server s remote registry. A lookup , however,

    can be done from any host.

  • 7/30/2019 java rmi tutorial

    12/18

    Page 8 Java RM I TutorialJDK 1.1 FCS, February 10, 1997

    1

    1.1.3 Write an A pplet that Uses the Remote Service

    The applet part of the distributed Hello World example remotely invokes the

    HelloServers sayHello method in order to get the string Hello World!,which is displayed when the applet runs. Here is the code for the applet:

    package examples.hello;

    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);

    }

    }

    1. The app let first gets a reference to the H elloServer from the server s

    registry, constructing the URL by u sing the getCodeBase method in

    conjunction with the getHost method.

    2. The app let remotely invokes the sayHello method of the HelloServerremote object and stores the return value from th e call (the string H ello

    World!) in a var iable named message.

    3. The applet invokes the paint method to d raw the ap plet on the display,

    causing the string Hello World! to be displayed.

    Note The constructed URL must include the host. Otherwise, the applets

    lookup will default to the client, and the AppletSecurityManager will

    throw an exception since the app let cann ot access the local system, but is

    instead limited to communicating only with the applet host.

  • 7/30/2019 java rmi tutorial

    13/18

    Getting Started Using RMI Page 9

    1

    1.1.4 Write the Web Page that Contains the Applet

    Here is the H TML code for th e web p age that references the Hello World

    applet:

    Hello World

    Hello World

    The message from the HelloServer is:

    Note the following:

    There needs to be an HTTP server running on the machine from which you

    want to download classes. The applets codebase attribute indicates the

    URL, as shown here:

    codebase="../.."

    The codebase in this examp le specifies a directory two levels above the

    directory from which the web page was itself loaded. Using this kind of

    relative path is usually a good idea.

    The ap plets code attribute specifies the fully pa ckage-qua lified n ame of the

    applet, in this example examples.hello.HelloApplet:

    code="examples.hello.HelloApplet"

    1.2 Compile and Deploy Class Files and HTM L Files

    The source code for the Hello World example is now complete and the

    $HOME/java/mysrc/hello directory has four files:

    Hello.java, wh ich contains th e source code for the H ello remote interface.

    HelloImpl.java, wh ich is the sou rce code for the H elloImpl rem ote object

    implementation, the server for the Hello World applet.

    HelloApplet.java, which is the source code for the applet.

    index.html, which is the web page that references the Hello World applet.

  • 7/30/2019 java rmi tutorial

    14/18

    Page 10 Java RM I TutorialJDK 1.1 FCS, February 10, 1997

    1

    In this section, you compile the .java source files to create .class files. You

    then run the rmic compiler to create stubs a nd skeletons. A stub is a client-

    side p roxy for a remote object w hich forward s RMI calls to the server-side

    skeleton, w hich in tur n forw ards th e call to the actual remote objectimplementation.

    When you use the javac an d rmic compilers, you must specify where the

    resulting class files should reside. For app lets, all files shou ld be in the ap plets

    codebase directory. In this chapter, this is $HOME/public_html/codebase.

    Note Some Web servers allow accessing a u sers pu blic_html d irectory via an

    HTTP URL constructed as http:/ / host/ ~username/ . If your Web server

    does not support this convention, you may use a file URL of the form

    file:/ / home/ username/ public_html.

    1.2.1 Compile the Java Source Files

    Make sure that the deployment directory $HOME/public_html/codebase

    and the development d irectory $HOME/java/mysrc/examples/hello are

    each visible via the local CLASSPATH on the d evelopment m achine.

    To comp ile the Java source files, run the javac command as follows:

    javac d $HOME/public_html/codebase

    Hello.java HelloImpl.java HelloApplet.java

    This command creates the directory examples/hello (if it does not already

    exist) in the directory $HOME/public_html/codebase . The command then

    wr ites to that directory the files Hello.class, HelloImpl.class, and

    HelloApplet.class. These are the remote interface, the server, and the

    applet respectively.

    1.2.2 Generate Stubs and Skeletons

    To create stub and skeleton files, run the rmic compiler on the names of

    compiled class files that contain remote object imp lementations. rmic takes

    one or more class names as inpu t and prod uces as outp ut class files of the form

    myImpl_Skel.class an d myImpl_Stub.class.

  • 7/30/2019 java rmi tutorial

    15/18

    Getting Started Using RMI Page 11

    1

    For example, to create the stub and skeleton for the H elloImpl remote object

    implementation, run rmic like this:

    rmic d $HOME/public_html/codebase examples.hello.HelloImpl

    The d option ind icates the root directory in wh ich to p lace the compiled stu b

    and skeleton files. So the p receding comman d creates the following files in the

    directory $HOME/public_html/codebase/examples/hello :

    HelloImpl_Stub.class

    HelloImpl_Skel.class

    Note that the generated stub implements exactly the same set of remote

    interfaces as the remote object itself. This means that a client can use the Javalanguag es built-in op erators for casting an d type checking. It also mean s that

    Java remote objects support true object-oriented polymorphism.

    1.2.3 Move the HTM L File to the Deployment Directory

    To m ake the w eb p age that references the ap plet visible to clients, the

    index.html file must be moved from the development d irectory to the

    codebase directory. For example:mv $HOME/java/mysrc/examples/hello/index.html

    $HOME/public_html/codebase/examples/hello

    1.2.4 Set Paths for Runt ime

    Make sure that the $HOME/public_html/codebase directory is available via

    the servers local CLASSPATH wh en you ru n the H elloImp l server.

    1.3 Start the Remote Object Registry, Server, and A pplet

    1.3.1 Start the RM I Bootstrap Registry

    The RMI registry is a simp le server-side bootstrap nam e server that a llows

    remote clients to get a reference to a remote object. It is typically used only to

    locate the fir st remote object an app lication need s to talk to. That object in tu rn

    will provide application specific support for finding other objects.

  • 7/30/2019 java rmi tutorial

    16/18

    Page 12 Java RM I TutorialJDK 1.1 FCS, February 10, 1997

    1

    To start the registry on the server, execute the rmiregistry comm and. This

    comm and produ ces no outp ut and is typically run in the background. For

    example, on Windows 95 or Windows NT:

    start rmiregistry

    (Use javaw if start is not available.)

    And on Solaris:

    rmiregistry &

    The registry by d efault run s on port 1099. To start th e registry on a different

    port, specify the port number in the command. For example, to start the

    registry on por t 2001 on Window s NT:start rmiregistry 2001

    If the registry is running on a port other than the default, you need to specify

    the port n um ber in the URL-based method s of the java.rmi.Naming class

    wh en m aking calls to the registry. For example, if the registry is run ning on

    port 2001 in the H ello World exam ple, here is the call required to bind the URL

    of the HelloServer to the remote object reference:

    Naming.rebind("//myhost:2001/HelloServer", obj);

    Similarly, the URL stored on the w eb page n eeds to sp ecify the nond efault port

    number, or else the applets attempt to look up the server in the registry will

    fail:

    Note You m ust stop an d restart the registry any time you m odify a remote

    interface or use mod ified/ add itional remote interfaces in a remote object

    implementation. Otherwise, the class bound in the registry will not match themodified class.

    1.3.2 Start the Server

    When starting th e server, the java.rmi.server.codebase property must be

    specified, so that references to the remote objects created by th e server can

    include the URL from which the stub class can be dynamically downloaded to

    the client.

  • 7/30/2019 java rmi tutorial

    17/18

    Getting Started Using RMI Page 13

    1

    The following command shows how to start the HelloImpl server, specifying

    this property:

    java Djava.rmi.server.codebase=http://myhost/~myusrname/codebase/

    examples.hello.HelloImpl &

    Note The trailing / in the codebase URL must be specified.

    A stub class is dynam ically loaded into a clients virtual m achine only w hen

    the class is not already available locally.

    1.3.3 Run the AppletOnce the registry and server are running, the applet can be run. An applet is

    run by loading its web page into a browser or app letviewer, as shown here:

    appletviewer

    http://myhost/~myusrname/codebase/examples/hello/index.html &

    After runn ing the ap pletviewer, you will see outp ut similar to the following on

    your d isplay:

  • 7/30/2019 java rmi tutorial

    18/18

    Page 14 Java RM I TutorialJDK 1.1 FCS, February 10, 1997

    1