RMI simple instance

Source: Internet
Author: User
Distributed object technology is mainly used to establish the application system framework and object components in a distributed heterogeneous environment. With the support of the application system framework, developers can encapsulate software functions as objects that are easier to manage and use. These objects can interoperate across different software and hardware platforms. Currently, the distributed interoperability standards mainly include Microsoft's COM/DCOM standards, sun's Java RMI standards, and OMG's CORBA standards.

Introduction to Java RMI

Remote Method Invocation (RMI) is a distributed object software package introduced in jdk1.1. Its appearance greatly simplifies the communication between Java applications in distributed heterogeneous environments.

To use RMI, you must construct four main classes: local interfaces of remote objects, remote object implementation, RMI clients, and RMI servers. The RMI server generates an instance for remote object implementation and registers it with a proprietary URL. The RMI client searches for the service object on the remote RMI server, converts it to the local interface type, and then uses it like a local object.

The following is a simple RMI instance. The RMI client outputs a statement through the method provided by the RMI server. Although the example is very simple, we have mastered the basic principles and methods of calling Java RMI. When implementing complex applications, we only need to improve the implementation class of remote objects.

RMI instance analysis
 
1. Remote Object Local interface declaration (rmioperate. Java) 

· This class is just an interface declaration. The RMI client can use it directly. The RMI server must implement it through a remote object and register an instance with a specific URL. · Remote interface Extensionjava.rmi.RemoteInterface. · Except for all application-specific exceptions, each method must be declared in the throws clausejava.rmi.RemoteException(OrRemoteException).

Hello. Java
/** @ Author javamxj (csdn blog) creation date: 2004-12-27 */import Java. RMI. *; // the RMI Local interface must derive the specific method declaration from the remote interface Hello extends remote {// interface. Note that the RemoteException string sayhello (string name) must be thrown) throws RemoteException ;}
  2. Remote Object implementation classThis class should implement the local interface of the remote service object called by the RMI client. It must inherit from unicastremoteobject, And the constructor should throw a RemoteException.

 Helloimpl. Java

 
/** @ Author javamxj (csdn blog) creation date: 2004-12-27 */
import java.rmi.*;
import javax.rmi.PortableRemoteObject;
public class HelloImpl extends PortableRemoteObject implements Hello {    
/* Constructor */
public HelloImpl() throws RemoteException {        
super();    
}    
/* Implement the 'sayhello () 'method declared in the Local interface */
public String sayHello(String message) throws RemoteException {        
System. Out. println ("On the RMI server, the client is calling the 'sayhello' method. ");
System.out.println("Hello  " + message);        
return message;    
}
}

  3. RMI server class

This class creates an instance of the remote object implementation class helloimpl, and then registers it through a proprietary URL. The so-called registration is to bind the helloimpl instance to the specified URL through the java. RMI. Naming. BIND () method or Java. RMI. Naming. rebind () method.

 Helloserver. Java

/** @ Author javamxj (csdn blog) creation date: 2004-12-27 */
import java.rmi.*;
public class HelloServer {    
public static void main(String[] args) {        
// Set the security mechanism on the server side
/*           
if (System.getSecurityManager() == null) {               
System.setSecurityManager(new RMISecurityManager());            
}        
*/                 
try {            
System. Out. println ("start rmi server ...");
/* Create an implementation instance for a remote object */
HelloImpl hImpl = new HelloImpl();            
System. Out. println ("register an instance to a proprietary URL ");
Naming.rebind("HelloService", hImpl);                        
System. Out. println ("waiting for the RMI client to call ...");
System.out.println("");        
} catch (Exception e) {            
System. Out. println ("error:" + E );
}    
}
}

Please note thatrebindThe following parameters of a method call:

  • The first parameter is in URL format.java.lang.StringThe location and name of the remote object.

    • You needmyhostThe value is changed to the server name or IP address. Otherwise, if it is omitted in the URL, the default host value is the current host, and you do not need to specify the protocol in the URL (for example,HelloServer").
    • In the URL, you can choose to provide the port number: for example, "//myhost:1234/HelloServer”。The default port is 1099. Unless the server creates a registration service program on port 1099 by default, you must specify the port number.
  • The second parameter is the object implementation reference from which the remote method is called.
  • RMI runtime will replacehImplThe actual remote object reference specified by the parameter. Remote implementation object (for exampleHelloImplInstances. Therefore, when the client performs a search in the Remote Object Registration Service Program of the server, it returns the object containing the stub program of this implementation.
  4. Rmi client class 

· RMI customers use the java. RMI. Naming. Lookup () method to find the RMI service object on the specified remote host. If it is found, convert it to the rmioperate type of the Local interface. It is different from CORBA in that the RMI client must know the URL of the host that provides the RMI service. This URL can be used through RMI: // host/path or RMI: // host: port/path. If the port number is omitted, 1099 is used by default. · The java. RMI. Naming. Lookup () method may produce three exceptions: Java. RMI. RemoteException, java. RMI. notboundexception, and java.net. malformedurlexception. All three exceptions must be captured.

Helloclient. Java

/** @ Author javamxj (csdn blog) creation date: 2004-12-27 */
import java.rmi.*;
public class HelloClient {    
public static void main(String[] args) {        
// Set the security mechanism on the server side
/*           
if (System.getSecurityManager() == null) {               
System.setSecurityManager(new RMISecurityManager());            
}        
*/             
/* Local host and default port by default */
String host = "localhost:1099";        
/* Set the host to the specified host with the input parameter */
if (args.length > 0)            
host = args[0];        
try {            
/* Locate the remote implementation object based on the specified URL */
/* "H" is an identifier. We will use it to point to the remote object implementing the "hello" interface */
Hello h = (Hello) Naming.lookup("rmi://" + host + "/HelloService");                        
System. Out. println ("remote object implementing the" hello "interface:" + H );
System. Out. println ("On the client, I started to call the 'sayhello' method on the RMI server ");
System. Out. println ("Welcome," + H. sayhello ("javamxj blog "));
} catch (Exception ex) {            
System. Out. println ("error" + ex );
}    
}
}
5. Compile the code and run the system:In the MS-DOS environment, create a D:/rmisample directory, copy the above four files to this directory, and then create two new folders under this directory: client and server (think of them as the client and server respectively ). (1 ). compile all source code D:/rmisample> javac *. java (2 ). generate client stubs and Server framework D:/rmisample> rmic helloimpl. This will generate helloimpl_stub.class and helloimpl_skel.class. ( Note: To view the source code of these two classes, you can use the "rmic-keep helloimpl" statement) (3 ). set hello. class, helloclient. class and helloimpl_stub.class are copied to the client directory, and hello. class, helloserver. copy class, helloimpl_skel.class, and helloimpl_stub.class to the server directory. (4) Start RMI Registration
D:/rmisample/Server> rmiregistry, there is also a running client .) (5). Run and call ● execute helloserver on the server
D:/rmisample/Server> JAVA helloserver ● run helloclient on the local client
D:/rmisample/client> JAVA helloclient ● run helloclient on a remote client (the host name or IP address of the RMI server must be specified)
Result of running rmiregistry and server in Java helloclient 222.222.34.34: the result of running the client again: note that the security management code is commented out in the above example. If you remove the comment, create a security policy file, for example, the file name is policy.txt. The content is as follows: Grant {
Permission java. Security. allpermission "","";
};
This is a simple security policy that allows anyone to do anything. For more critical applications, you must specify more detailed security policies. Copy the file to the client and server directories and run: D:/rmisample/Server> JAVA -djava.security.policypolicpolicy.txt helloserverd:/rmisample/client> JAVA -djava.security.policypolicpolicy.txt helloclient

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.