Java RMI - Tutorialspoint

1y ago
8 Views
1 Downloads
827.71 KB
17 Pages
Last View : 24d ago
Last Download : 6m ago
Upload by : Camille Dion
Transcription

Java RMI

Java RMIAbout the TutorialRMI stands for Remote Method Invocation. It is a mechanism that allows an objectresiding in one system (JVM) to access/invoke an object running on another JVM.RMI is used to build distributed applications; it provides remote communication betweenJava programs. It is provided in the package java.rmi.AudienceThis tutorial has been prepared for beginners to make them understand the basics ofRemote Method Invocation in Java.PrerequisitesFor this tutorial, it is assumed that the readers have a prior knowledge of Javaprogramming language. In some of the programs of this tutorial, we have used JavaFX forGUI purpose. So, it is recommended that you go through our JavaFX tutorial beforeproceeding further. http://www.tutorialspoint.com/javafx/Copyright & Disclaimer Copyright 2017 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of Tutorials Point (I)Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republishany contents or a part of contents of this e-book in any manner without written consentof the publisher.We strive to update the contents of our website and tutorials as timely and as precisely aspossible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of ourwebsite or its contents including this tutorial. If you discover any errors on our website orin this tutorial, please notify us at contact@tutorialspoint.comi

Java RMITable of ContentsAbout the Tutorial . iAudience . iPrerequisites . iCopyright & Disclaimer . iTable of Contents . iiJAVA RMI INTRODUCTION . 1Architecture of an RMI Application . 1Working of an RMI Application . 2Marshalling and Unmarshalling . 2RMI Registry . 3Goals of RMI . 3JAVA RMI RMI APPLICATION . 4Defining the Remote Interface . 4Developing the Implementation Class (Remote Object) . 5Developing the Server Program . 5Developing the Client Program . 7Compiling the Application . 8Executing the Application . 9JAVA RMI GUI APPLICATION . 11Server Program . 15Client Program . 16Steps to Run the Example . 17ii

Java RMIJAVA RMI DATABASE APPLICATION . 20Creating a Student Class. 20Server Program . 24Client Program . 25Steps to Run the Example . 26iii

JAVA RMI INTRODUCTIONJava RMIRMI stands for Remote Method Invocation. It is a mechanism that allows an object residingin one system (JVM) to access/invoke an object running on another JVM.RMI is used to build distributed applications; it provides remote communication between Javaprograms. It is provided in the package java.rmi.Architecture of an RMI ApplicationIn an RMI application, we write two programs, a server program (resides on the server) anda client program (resides on the client). Inside the server program, a remote object is created and reference of that object ismade available for the client (using the registry). The client program requests the remote objects on the server and tries to invoke itsmethods.The following diagram shows the architecture of an RMI application.4

Java RMILet us now discuss the components of this architecture. Transport Layer This layer connects the client and the server. It manages theexisting connection and also sets up new connections. Stub A stub is a representation (proxy) of the remote object at client. It resides inthe client system; it acts as a gateway for the client program. Skeleton This is the object which resides on the server side. stub communicateswith this skeleton to pass request to the remote object. RRL (Remote Reference Layer) It is the layer which manages the referencesmade by the client to the remote object.Working of an RMI ApplicationThe following points summarize how an RMI application works: When the client makes a call to the remote object, it is received by the stub whicheventually passes this request to the RRL. When the client-side RRL receives the request, it invokes a method called invoke() ofthe object remoteRef. It passes the request to the RRL on the server side. The RRL on the server side passes the request to the Skeleton (proxy on the server)which finally invokes the required object on the server. The result is passed all the way back to the client.Marshalling and UnmarshallingWhenever a client invokes a method that accepts parameters on a remote object, theparameters are bundled into a message before being sent over the network. Theseparameters may be of primitive type or objects. In case of primitive type, the parameters areput together and a header is attached to it. In case the parameters are objects, then they areserialized. This process is known as marshalling.At the server side, the packed parameters are unbundled and then the required method isinvoked. This process is known as unmarshalling.5

Java RMIRMI RegistryRMIregistry is a namespace on which all server objects are placed. Each time the servercreates an object, it registers this object with the RMIregistry (using bind() or reBind()methods). These are registered using a unique name known as bind name.To invoke a remote object, the client needs a reference of that object. At that time, the clientfetches the object from the registry using its bind name (using lookup() method).The following illustration explains the entire process:Goals of RMIFollowing are the goals of RMI: To minimize the complexity of the application To preserve type safety6

Java RMI Distributed garbage collection Minimize the difference between working with local and remote objects7

JAVA RMI RMI APPLICATIONJava RMITo write an RMI Java application, you would have to follow the steps given below: Define the remote interface Develop the implementation class (remote object) Develop the server program Develop the client program Compile the application Execute the applicationDefining the Remote InterfaceA remote interface provides the description of all the methods of a particular remote object.The client communicates with this remote interface.To create a remote interface – Create an interface that extends the predefined interface Remote which belongs tothe package. Declare all the business methods that can be invoked by the client in this interface. Since there is a chance of network issues during remote calls, an exception namedRemoteException may occur; throw it.Following is an example of a remote interface. Here we have defined an interface with thename Hello and it has a method called printMsg().import java.rmi.Remote;import java.rmi.RemoteException;// Creating Remote interface for our applicationpublic interface Hello extends Remote {void printMsg() throws RemoteException;}8

Java RMIDeveloping the Implementation Class (Remote Object)We need to implement the remote interface created in the earlier step. (We can write animplementation class separately or we can directly make the server program implement thisinterface.)To develop an implementation class – Implement the interface created in the previous step. Provide implementation to all the abstract methods of the remote interface.Following is an implementation class. Here, we have created a class named ImplExampleand implemented the interface Hello created in the previous step and provided body for thismethod which prints a message.// Implementing the remote interfacepublic class ImplExample implements Hello{// Implementing the interface methodpublic void printMsg() {System.out.println("This is an example RMI program");}}Developing the Server ProgramAn RMI server program should implement the remote interface or extend the implementationclass. Here, we should create a remote object and bind it to the RMIregistry.To develop a server program – Create a class that extends the implementation class implemented in the previousstep. (or implement the remote interface) Create a remote object by instantiating the implementation class as shown below. Export the remote object using the method exportObject() of the class namedUnicastRemoteObject which belongs to the package java.rmi.server. Get the RMI registry using the getRegistry() method of the LocateRegistry classwhich belongs to the package java.rmi.registry. Bind the remote object created to the registry using the bind() method of the classnamed Registry. To this method, pass a string representing the bind name and theobject exported, as parameters.9

Java RMIFollowing is an example of an RMI server program.import java.rmi.registry.Registry;import java.rmi.registry.LocateRegistry;import java.rmi.RemoteException;import java.rmi.server.UnicastRemoteObject;public class Server extends ImplExample{public Server() {}public static void main(String args[]) {try {// Instantiating the implementation classImplExample obj new ImplExample();// Exporting the object of implementation class// (here we are exporting the remote object to the stub)Hello stub (Hello) UnicastRemoteObject.exportObject(obj, 0);// Binding the remote object (stub) in the registryRegistry registry , stub);System.err.println("Server ready");} catch (Exception e) {System.err.println("Server exception: " e.toString());e.printStackTrace();}}10

Java RMI}Developing the Client ProgramWrite a client program in it, fetch the remote object and invoke the required method usingthis object.To develop a client program – Create a client class from where you want invoke the remote object. Get the RMI registry using the getRegistry() method of the LocateRegistry classwhich belongs to the package java.rmi.registry. Fetch the object from the registry using the method lookup() of the class Registrywhich belongs to the package java.rmi.registry. To this method you need to pass astring value representing the bind name as a parameter. This will return you theremote object down cast it. The lookup() returns an object of type remote, down cast it to the type Hello. Finally invoke the required method using the obtained remote object.Following is an example of an RMI client program.import java.rmi.registry.LocateRegistry;import java.rmi.registry.Registry;public class Client {private Client() {}public static void main(String[] args) {try {// Getting the registryRegistry registry LocateRegistry.getRegistry(null);// Looking up the registry for the remote objectHello stub (Hello) registry.lookup("Hello");11

Java RMI// Calling the remote method using the obtained objectstub.printMsg();// System.out.println("Remote method invoked");} catch (Exception e) {System.err.println("Client exception: " e.toString());e.printStackTrace();}}}Compiling the ApplicationTo compile the application – Compile the Remote interface. Compile the implementation class. Compile the server program. Compile the client program.Or,Open the folder where you have stored all the programs and compile all the Java files asshown below.Javac *.java12

Java RMIExecuting the ApplicationStep 1: Start the rmi registry using the following command.start rmiregistryThis will start an rmi registry on a separate window as shown below.13

Java RMIStep 2: Run the server class file as shown below.Java ServerStep 3: Run the client class file as shown below.java Client14

Java RMIVerification: As soon you start the client, you would see the following output in the server.15

Java RMIEnd of ebook previewIf you liked what you saw Buy it from our store @ https://store.tutorialspoint.com16

Java RMI 4 RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing in one system (JVM) to access/invoke an object running on another JVM. RMI is used to build distributed applications; it provides remote communication between Java programs. It is provided in the package java.rmi. Architecture of an RMI Application

Related Documents:

java.io Input and output java.lang Language support java.math Arbitrary-precision numbers java.net Networking java.nio "New" (memory-mapped) I/O java.rmi Remote method invocations java.security Security support java.sql Database support java.text Internationalized formatting of text and numbers java.time Dates, time, duration, time zones, etc.

Java remote protocol RMI: Java programming interface (API) for remote communications, runs on JRMP protocol. CORBA: communication architecture, uses IIOP protocol. Works cross-language ( C , Java ) This research talks about: RMI-JRMP. Most widely used, commonly referred to as simply RMI RMI-IIOP. Java CORBA programming model

Java Version Java FAQs 2. Java Version 2.1 Used Java Version This is how you find your Java version: Start the Control Panel Java General About. 2.2 Checking Java Version Check Java version on https://www.java.com/de/download/installed.jsp. 2.3 Switching on Java Console Start Control Panel Java Advanced. The following window appears:

Java provides two mechanisms for distributed computing:!! (1) !Socket-based communication ! (java.net)!!Sockets are the endpoints of two-way connections between two distributed components that communicate with each other.!! (2)!Remote method invocation (RMI)! (java.rmi)!!RMI allows distributed components to be manipulated

Sistemas Distribuidos RMI Remote Method Invocation Java RMI Prof. Alejandro Reyes Ortiz. Invocación de Métodos Remotos (RMI) qEl mecanismo RMI permite que una aplicación se comunique con objetos que residen en programas que se ejecutan en máquinas remotas.

Java Logging Overview Other Core Libraries Guides Internationalization Overview in Java Platform, Standard Edition Internationalization Guide Security Related Topics Serialization Filtering RMI: - RMI Security Recommendations in Java Platform, Standard Edition Java Remote Method Invocation User's Guide

Many productive parallel/distributed programming libs: Java shared memory programming (high level facilities: Concurrency framework) Java Sockets Java RMI Message-Passing in Java (MPJ) libraries Apache Hadoop Guillermo López Taboada High Performance Computing in Java and the Cloud . Guillermo López Taboada High Performance Computing in Java .

aliments contenant un additif alimentaire des dispositions des alinéas a) et d) du paragraphe 4(1) ainsi que du paragraphe 6(1) de la Loi sur les aliments et drogues de même que, s'il y a lieu, des articles B.01.042, B.01.043 et B.16.007 du Règlement sur les aliments et drogues uniquement en ce qui a trait