JAVA improvement stage: RMI step by step

Source: Internet
Author: User
Tags mul

Remote Method Invocation (RMI) is the pillar of Enterprise JavaBeans and a convenient way to build distributed Java applications. RMI is very easy to use, but it is very powerful.

The foundation of RMI is interfaces. the RMI architecture is based on an important principle: the specific implementation of defining interfaces and defining interfaces is separated. The following example shows how to create a simple Remote Computing Service and a customer program that uses it.

A normally working RMI system consists of the following parts:
Remote Service Interface Definition
Implementation of remote service interfaces
Pile (Stub) and frame (Skeleton) files
A server running remote services
An RMI naming service that allows the client to discover this remote service
File provider (an HTTP or FTP Server)
A client program that requires this remote service
Next we will build a simple RMI system step by step. First, create a new folder on your machine to store the files we created. For simplicity, we only use one folder to store the client and server code, and run the server and client in the same directory.

If all the RMI files have been designed, you need to take the following steps to generate your system:

1. Compile and compile the Java code of the interface
2. Compile and compile the Java code implemented by the interface
3. Generate Stub and Skeleton files from the interface implementation class.
4. Compile the master program of the remote service
5. Write the RMI client program
6. Install and run the RMI system

1. Interface
The first step is to establish and compile the Java code of the service interface. This interface defines all functions that provide remote services. The following is the source program:

// Calculator. java
// Define the interface
Import java. rmi. Remote;

Public interface Calculator extends Remote
{
Public long add (long a, long B)
Throws java. rmi. RemoteException;

Public long sub (long a, long B)
Throws java. rmi. RemoteException;

Public long mul (long a, long B)
Throws java. rmi. RemoteException;

Public long div (long a, long B)
Throws java. rmi. RemoteException;
}
Note that this interface is inherited from Remote. Each defined method must throw a RemoteException object.

Create this file, store it in the directory just now, and compile it.

> Javac Calculator. java

2. Specific implementation of interfaces

Next, we need to write the specific implementation of the remote service. This is a CalculatorImpl file:

// CalculatorImpl. java
// Implementation
Import java. rmi. server. UnicastRemoteObject

Public class CalculatorImpl extends UnicastRemoteObject implements Calculator
{

// This implementation must have an explicit constructor and throw a RemoteException.
Public CalculatorImpl ()
Throws java. rmi. RemoteException {
Super ();
}

Public long add (long a, long B)
Throws java. rmi. RemoteException {
Return a + B;
}

Public long sub (long a, long B)
Throws java. rmi. RemoteException {
Return a-B;
}

Public long mul (long a, long B)
Throws java. rmi. RemoteException {
Return a * B;
}

Public long div (long a, long B)
Throws java. rmi. RemoteException {
Return a/B;
}
}
Similarly, save the file in your directory and compile it.

This implementation class uses UnicastRemoteObject to connect to the RMI system. In our example, we directly inherit from the class UnicastRemoteObject. In fact, we do not have to do this. If a class is not inherited from UnicastRmeoteObject, you must use its exportObject () method to connect to RMI.

If a class inherits from UnicastRemoteObject, it must provide a constructor and declare to throw a RemoteException object. When this constructor calls super (), it activates the code in UnicastRemoteObject for a long time to complete the RMI connection and remote object initialization.

3. Stubs and Skeletons)

The next step is to use the RMI compiler rmic to generate the pile and framework files. This compilation runs on the remote service implementation class file.

> Rmic CalculatorImpl

Run the above command in your directory. After successfully executing the above command, you can find a file named Calculator_stub.class. If you are using Java2SDK, you can also find the file named Calculator_Skel.class.

4. Host servers

The remote RMI service must run on a server. The CalculatorServer class is a very simple server.

// CalculatorServer. java
Import java. rmi. Naming;

Public class CalculatorServer {

Public CalculatorServer (){
Try {
Calculator c = new CalculatorImpl ();
Naming. rebind ("rmi: // localhost: 1099/CalculatorService", c );
} Catch (Exception e ){
System. out. println ("Trouble:" + e );
}
}

Public static void main (String args []) {
New CalculatorServer ();
}
}
Create this server program, save it to your directory, and compile it.

5. Client

The client source code is as follows:

// CalculatorClient. java

Import java. rmi. Naming;
Import java. rmi. RemoteException;
Import java.net. MalformedURLException;
Import java. rmi. NotBoundException;

Public class CalculatorClient {

Public static void main (String [] args ){
Try {
Calculator c = (Calculator)
Naming. lookup (
"Rmi: // localhost
/CalculatorService ");
System. out. println (c. sub (4, 3 ));
System. out. println (c. add (4, 5 ));
System. out. println (c. mul (3, 6 ));
System. out. println (c. div (9, 3 ));
}
Catch (MalformedURLException murle ){
System. out. println ();
System. out. println (
"MalformedURLException ");
System. out. println (murle );
}
Catch (RemoteException re ){
System. out. println ();
System. out. println (
"RemoteException ");
System. out. println (re );
}
Catch (NotBoundException nbe ){
System. out. println ();
System. out. println (
"NotBoundException ");
System. out. println (nbe );
}
Catch (
Java. lang. ArithmeticException
AE ){
System. out. println ();
System. out. println (
"Java. lang. ArithmeticException ");
System. out. println (AE );
}
}
}
Save the client program to your directory (note that this directory is created at the beginning, and all our files are under that directory) and compile it.
6. Run the RMI system

Now we have created all the files required to run this simple RMI system. Now we can finally run this RMI system! To enjoy it.

We run this system in the command console. You must open three console windows, one running server, one running client, and one running RMIRegistry.

First, run the registration program RMIRegistry. You must run the registration program in the directory containing the class you just wrote.

> Rmiregistry

Well, if this command is successful, the Registration Program has started to run. Don't worry about it. Now switch to another console. In the second console, we run the server CalculatorService, because the RMI security mechanism will work on the server, you must add a security policy. The following are examples of corresponding security policies:
Grant {
Permission java. security. AllPermission "","";
};
Note: This is the simplest security policy that allows anyone to do anything. For your more critical applications, you must specify more detailed security policies.
To run the server, you need all the class files except the client class (CalculatorClient. class. After confirming that the security policy is in the policy.txt file, run the following command to run the server.

> Java -djava.security.policypolicpolicy.txt CalculatorServer

The server started to work and loaded the interface implementation to the memory to wait for the client connection. Now switch to the third console and start our client.
To run client programs on other machines, you need a remote interface (Calculator. class) and a stub (CalculatorImpl_Stub.class ). Run the following command to run the client:

Prompt> java -djava.security.policypolicpolicy.txt CalculatorClient

If all of these operations are successful, you should see the following output:
1
9
18
3
If you see the above output, congratulations, you have succeeded. You have successfully created an RMI system and made it work correctly. Even if you are running on the same computer, RMI uses your network stack and TCP/IP for communication, and runs on three different Java virtual machines. This is a complete RMI system.

Related Article

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.