Java RMI Remote Method call detailed __java

Source: Internet
Author: User
Tags garbage collection stub
Java RMI Remote method call detailed"Respect original, reprint please indicate source" http://blog.csdn.net/guyuealian/article/details/51992182 First, Java RMI mechanism:    Remote method call RMI (remote methods invocation) is a method that allows an object that runs on one Java virtual machine to invoke objects running on another Java virtual machine.        The two virtual machines can be in different processes running on the same computer, or they can be running on different computers on the network. Java Rmi:java Remote method invocation, Java RMI (Java Remote methods invocation) is an application programming interface for implementing remote procedure calls in the Java programming language. It makes it possible for programs running on a client computer to invoke objects on a remote server. The remote Method invocation attribute enables Java programmers to distribute operations in a network environment. The whole purpose of RMI is to simplify the use of remote interface objects as much as possible.
Instead, RPC is a remote procedure call, which can be used by a process that invokes another process (most likely on another remote host), providing a Procedure distribution capacity of the process。 Java RMI is a step forward on the basis of RPC, which provides communication between distributed objects(1) RMI Framework      "Reference" Java Network programming refinement Sun Weichen, this book is suitable for the introductory Learning RMI Framework Foundation Http://wenku.baidu.com/view/90171bd03186bceb19e8bbdc.html?fro The M=search RMI framework encapsulates all the underlying communication details and addresses common issues such as marshalling, distributed garbage collection, security checks, and concurrency. With ready-made frameworks, developers simply focus on developing a variety of local objects and remote objects that are relevant to a particular problem area.

To understand the RMI principle, first understand the stub and skeleton two concepts.
(2) Stub and skeleton  The RMI framework takes the agent to take care of the details of communication between the client and the remote object through the socket. The RMI framework generates client and server-side proxies for remote objects, respectively. The proxy class located on the client is called a stub, and the proxy class on the server side is called the Skeleton (skeleton).

"Relevant information" "http://blog.csdn.net/smcwwh/article/details/7080997" (stub) and Skel in the first glimpse of RMI (Remote method invocation) Eton (skeleton) acts as a proxy role in RMI and is used in real-world development to hide differences between systems and networks, a feature that is transparent to programmers in RMI development. Stub encodes remote commands for the client and sends them to the server.      And skeleton is to decode the remote command, call the server's remote object method, the result in the code to the stub, and then the stub and then decode the return call results to the client. The implementation process of the RMI remote procedure call is shown in the following illustration:
The basic principles of the RMI framework are as follows: The agent pattern is applied to encapsulate the details of the local stub communicating with the real remote object
"Reference" Java RMI Framework (remote method call) http://haolloyin.blog.51cto.com/1177454/332426 "Java RMI principles detailed" http://blog.csdn.ne t/xinghun_4/article/details/45787549
Second, Java RMI Simple Example do not worry, slowly analysis ~ Concrete code in the following, with example code download: http://download.csdn.net/detail/guyuealian/9583633Roughly speaking, creating an RMI application involves the following steps: (1) Creating a remote interface: inheriting the Java.rmi.Remote interface.
(2) Create a remote class: Implement a remote interface.
(3) Create a server program: Create a remote object and register the remote object with the Createregistry () method. The remote object is bound to the specified namespace (URL) through the bind or Rebind method.
(4) Create a client: Look for a remote object through the lookup () method, and make a remote method call to analyze each step in detail:
(1) Create a remote interface: inherits the Java.rmi.Remote interface. A remote method is declared in the remote interface that can be accessed by a client program. The RMI specification requires that the class that the remote object belongs to implement a remote interface, and that the remote interface meets the following conditions:
(a) direct or indirect inheritance of the Java.rmi.Remote interface. (b) All method declarations in the interface throw java.rmi.RemoteException.
(2) Create a remote class: Implement a remote interface. The remote class is the class to which the remote object belongs. The RMI specification requires that the remote class must implement a remote interface. In addition, to make an instance of a remote class become a remote object that can serve remote clients, you can export it to a remote object in one of the following two ways:
(a) The first way to export to a remote object is to enable the remote class to implement the remote interface while inheriting the Java.rmi.server.UnicastRemoteObject class, and the method of constructing the remote class must declare the remoteexception thrown. This is the most common way to do this, and the following example takes this approach.
public class Remoteimpl extends UnicastRemoteObject implements Remoteinterface
(b) The second way to export to a remote object: If a remote class has inherited other classes and cannot inherit the UnicastRemoteObject class, then the static ExportObject () method of the UnicastRemoteObject class can be called in the constructor method , similarly, the constructor method of the remote class must declare the throw remoteexception.
public class Remoteimpl extends Otherclass implements remoteinterface{
  private String name;
  Public Remoteimpl (String name) throws remoteexception{
    This.name=name;
    Unicastremoteobject.exportobject (this,0);
  }
The Unicastremoteobject.exportobject (this,0) method is called in the constructor Remoteimpl to export itself as a remote object. ExportObject () is the UnicastRemoteObject static method, the source code is:
    protected unicastremoteobject (int port) throws RemoteException
    {
        this.port = port;
        ExportObject (Remote) this, port;
    }
    public static remote ExportObject (remote obj, int port)
        throws RemoteException
    {return
        exportobject (obj, New Unicastserverref (port);
    }
ExportObject (remote obj, int port), which is responsible for exporting the object specified by parameter obj as a remote object, giving it a stub, and listening to a remote client's method call request; parameter port instructs the port to listen on, if the value is 0, Indicates that any one of the anonymous ports is listening.
(3) Create a server program: Create a remote object, register the remote object in the Rmiregistry registry, and bind to the specified URL.        RMI uses a naming service mechanism to enable clients to locate a remote object on the server. There is a Rmiregistry.exe program in the bin subdirectory of the JDK's installation directory, which is the registry program that provides the naming service.
One of the main tasks of a server program is to register a remote object with the Rmiregistry registry. Beginning with the JDK1.3 version, the RMI naming Service APIs are consolidated into Jndi (Java naming and directory Interface,java name and directory interfaces). In Jndi, the Javax.naming.Context interface declares a way to register, find, and unregister objects:
"1" bind (String name,object obj): Registers the object, binds the object with a name named name, where the name is actually the URL format. If the name is already bound to another object, it throws a namealreadyboundexception.
"2" rebind (String name,object obj): Registers the object, binds the object with a name. If the name is already bound to another object, it does not throw a namealreadyboundexception, but instead overwrites the object specified by the current argument obj to the original object.
"3" lookup (String name): Finds an object that returns the object that is bound to the name specified by the parameter name.
' 4 ' Unbind (String name): Unregister an object, canceling the binding of the object to the name. Registering a remote object RemoteObj2 key code as follows:
Remoteinterface remoteObj2 = new Remoteimpl ();//Create remote object
context NamingContext = new InitialContext ();//Initialize named content
Locateregistry.createregistry (8892);//creates and exports registry instances on the local host and accepts requests on the specified port
namingcontext.rebind ("Rmi://localhost : 8892/remoteobj2 ", remoteObj2);//Register object, which binds the object to a name.
However, in the JDK1.3 version or lower version, you need to use java.rmi.Naming to register the remote object, and the registration code replaces the following:
Remoteinterface remoteobj = new Remoteimpl ();
Locateregistry.createregistry (8891);
Naming.rebind ("Rmi://localhost:8891/remoteobj", remoteobj);
(4) Create a client: Find a remote object by using the lookup () method, and make a remote method callThe key code is as follows:
Context NamingContext = new InitialContext ()//initialization of named content
remoteinterface RmObj2 = (remoteinterface) Namingcontext.lookup ("Rmi://localhost:8892/remoteobj2");//Gets the stub object System.out.println of the remote object
( Rmobj2.dosomething ());//By remote object, call DoSomething method
In the JDK1.3 version or lower version, the following method is invoked;
Remoteinterface rmobj = (remoteinterface) naming.lookup ("Rmi://localhost:8891/remoteobj");
System.out.println (Rmobj.dosomething ());
Example specific Code: 1. Create a remote interface: inherits the Java.rmi.Remote interface.
Package RMI;
Import Java.rmi.Remote;
Import java.rmi.RemoteException;
Declares a remote interface remoteinterface, which must inherit a
method that needs to be invoked remotely in the remote interface//interface, and must throw RemoteException exception public
interface Remoteinterface extends Remote {
	//Declare a dosomething method public
	String dosomething () throws remoteexception;
	Declares a calculation method Calculate public
	int Calculate (int num1, int num2) throws remoteexception;
In Java, as long as a class extends the Java.rmi.Remote interface, it becomes a remote object that exists on the server side for the client to access and provide a certain service. Javadoc Description: The Remote interface is used to identify an interface whose methods can be invoked from a non-local virtual machine. Any remote object must implement this interface directly or indirectly. Only these methods specified in the remote interface (the extended Java.rmi.Remote interface) can be invoked remotely. Note: A method that needs to be invoked remotely in an interface must throw a RemoteException exception. 2. Creating a remote class: Implementing a remote interface
Package RMI;
Import java.rmi.RemoteException;
Import Java.rmi.server.UnicastRemoteObject;
Implement remote interface Remoteinterface, and inherit unicastremoteobject
//Note remoteobject This class, realize the serializable, remote these two interfaces
public Class Remoteimpl extends UnicastRemoteObject implements Remoteinterface {
	//This implementation must have an explicit constructor. And to throw a RemoteException exception public
	Remoteimpl () throws remoteexception {
	}
	//Implementation DoSomething method
	public String dosomething () throws RemoteException {return
		"OK, can do ...";
	}
	Implements the Calculate method, returns the computed result public
	int Calculate (int num1, int num2) throws RemoteException {return
		(NUM1 + num2); c16/>}
}
The remote object must implement the Java.rmi.server.UniCastRemoteObject class, which generates stubs and skeleton in the constructor of the class, so that when the client accesses the remote object, The remote object will transmit a copy of itself to the client in the form of a socket, The copy that the client obtains at this time is called a stub ( stub), and the remote object that the server side itself already exists is called the skeleton (skeleton)。 In fact, the stub at this time is a client agent, used for communication with the server side, and the skeleton can also be considered as a server-side agent, used to receive the client's request after the call to the remote method to respond to the client's request. 3. Create a server program: Register the remote object in the Rmiregistry registry.Providing remote Object Services to clients
Package rmi2;
Import Javax.naming.Context;
Import Javax.naming.InitialContext;

Import RMI. Remoteinterface;

public class Clienttest {public
	static void Main (String args[]) {
		try {context
			NamingContext = new Initialco ntext ()//initializes the named content
			remoteinterface RmObj2 = (remoteinterface) namingcontext
					. Lookup ("rmi://localhost:8892/ RemoteObj2 ");//Get the stub object
			System.out.println (rmobj2.dosomething ()) of the remote object;//Call dosomething method
			via remote object SYSTEM.OUT.PRINTLN ("The remote server evaluates to:" + rmobj2.calculate (2));
		catch (Exception e) {
		}
	}
}
In the JDK1.3 version or lower version, the following way registration;
Package RMI;
Import java.net.MalformedURLException;
Import java.rmi.AlreadyBoundException;
Import java.rmi.Naming;
Import java.rmi.RemoteException;
Import Java.rmi.registry.LocateRegistry;
In the JDK1.3 version or lower version, you need to use java.rmi.Naming to register the remote object//To create the RMI registry, start the RMI service, and register the remote objects in the RMI registry.  public class Rmiserver {public static void main (String args[]) throws Java.rmi.AlreadyBoundException {try {//

			Creating a remote object Remoteobj essentially implicitly generates stubs and skeleton, and returns a stub proxy reference remoteinterface Remoteobj = new Remoteimpl (); Create and start the RMI service locally, the created registry services will not bind the object to the remote registry on the specified port, the listening request//Java default port is 1099, and the registry creation is missing Locateregistry.createregis

			Try (8891);
			Register the remote object on the RMI registration server and name it remoteobj (name customizable, client to correspond)//binding URL standard format is: Rmi://host:port/name (where the protocol name can be omitted, the following two kinds of writing are correct) Naming.rebind ("Rmi://localhost:8891/remoteobj", remoteobj)//bind the stub agent to the URL of the Registry service//Naming.bind ("//

			Localhost:8880/remoteobj ", remoteobj); System.out.println (">>>>>info: Remote Ihello Object binding succeeded.
		");
		catch (RemoteException e) {	SYSTEM.OUT.PRINTLN ("Creating a remote object has an exception.)
			");
		E.printstacktrace (); A URL malformed exception occurred with catch (Malformedurlexception e) {System.out.println.
			");
		E.printstacktrace (); }
	}
}
The Rmiserver class primarily implements registering remote objects and providing remote Object services to clients. The remote object was created on the remote service, and you cannot know exactly the name of the object on the remote server. However, after registering a remote object with the RMI service, the client can request the stub of the remote service object through the RMI service, and the remote service object can be accessed by using the stub agent.
4. Client codeServer-side code has been written all over, and the interface remoteinterface of the servers is packaged into jars for use in client-side projects. Project--> Right-click--> Export-->jar-> Select remoteinterface.java-->finish; about how clients can import jar packs, see here: http://jingyan.baidu.com /article/ca41422fc76c4a1eae99ed9f.html

Package rmi2;
Import Javax.naming.Context;
Import Javax.naming.InitialContext;

Import RMI. Remoteinterface;
public class Clienttest {public
	static void Main (String args[]) {
		try {context
			NamingContext = new Initialco ntext ()//initializes the named content
			remoteinterface RmObj2 = (remoteinterface) namingcontext
					. Lookup ("rmi://localhost:8892/ RemoteObj2 ");//Get the stub object
			System.out.println (rmobj2.dosomething ()) of the remote object;//Call dosomething method
			via remote object SYSTEM.OUT.PRINTLN ("The remote server evaluates to:" + rmobj2.calculate (2));
		catch (Exception e) {
		}
	}
}
In the JDK1.3 version or lower version, the following method calls the
Import java.net.MalformedURLException;
Import java.rmi.Naming;
Import java.rmi.NotBoundException;
Import java.rmi.RemoteException;

public class Clienttest {public
	static void Main (String args[]) {
		try {
			//Find an object named Remoteobj in the RMI service registry. And the method on which it is invoked
			//The client obtains a remote reference to the remote object via the naming service naming
			remoteinterface rmobj = (remoteinterface) naming
					. Lookup ("RMI ://localhost:8881/remoteobj ");
			System.out.println (Rmobj.dosomething ());
			SYSTEM.OUT.PRINTLN ("The remote server evaluates to:" + rmobj.calculate (1, 2));
		catch (Notboundexception e) {
			e.printstacktrace ();
		} catch (Malformedurlexception e) {
			E.printstacktrace ();
		} catch (RemoteException e) {
			e.printstacktrace ();}}}
Output results:
OK, can do ...
The remote server calculated the result as: 92
Example code download: http://download.csdn.net/detail/guyuealian/9583633




If you think that this post to help you, but also hope that the generous support, I will redouble my efforts to continue the ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.