74.JAVA Programming Ideas--remote methods

Source: Internet
Author: User

74.JAVA Programming Ideas--remote methods

To execute code on other machines over the network, the traditional approach is not only difficult to learn and master, but also extremely error-prone. The best way to think about this problem is that some objects are located exactly on another machine, and we can send them a message and get the results back, just as those objects are on their own local machine. It is this abstraction that is used by the remote Method invocation (RMI) of Java 1.1. will lead you through some necessary steps to create your own RMI object.

1 Remote Interface Concept

RMI has a strong reliance on interfaces. When we need to create a remote object, we pass an interface to hide the implementation details of the base. So when a client gets a handle to a remote object, they really get an interface handle. This handle is directly connected to some local root code, which is responsible for communicating over the network. But we don't care about these things, just send a message through our own interface handle.

When you create a remote interface, you must adhere to the following rules:

(1) The remote interface must be a public attribute (cannot have "package access"; in other words, it cannot be "friendly"). Otherwise, once the client attempts to mount a remote object that implements the remote interface, an error is obtained.

(2) The remote interface must extend the interface java.rmi.Remote.

(3) In addition to the violations associated with the application itself, each method in the remote interface must declare java.rmi.RemoteException in its own throws clause.

(4) A remote object that is passed as a parameter or a return value (whether direct or embedded in a local object) must be declared as a remote interface and cannot be declared as an implementation class.

The following is a simple example of a remote interface that represents an exact timing service:

import java.rmi.*;

Interface Perfecttimeiextends Remote {

long getperfecttime ()throws remoteexception;

}/// :~

It is superficially similar to other interfaces, except that it extends the remote and all its methods "throw" out

RemoteException (remote violation). Remember that the interface and all of its methods are public.

2 Implementation of the remote interface

The server must contain a class that extends the UnicastRemoteObject and implements the remote interface. This class can also contain additional methods, but the client can only use methods from the remote interface. This is obvious, because the client gets just a handle to the interface, not the class that implements it.

You must explicitly define the builder for the remote object, even if you are only ready to define a default builder, and use it to invoke the underlying class builder. It must be explicitly written, as it must "throw" out remoteexception violations.

The following is a list of the implementation procedures for remote interface Perfecttime:

2.1 Code

import java.rmi.*;

import java.rmi.server.*;

Import java.rmi.registry. *;

Import java.net. *;

Public class Perfecttime extends UnicastRemoteObjectimplementsPerfecttimei {

//implementation of the interface:

Public longgetperfecttime () throws remoteexception {

return System. Currenttimemillis ();

}

//Mustimplement constructor to throw

//remoteexception:

Public Perfecttime ()throws remoteexception {

//Super ();//called Automatically

}

//registration for RMI serving:

Public staticvoidmain (string[]args) {

System. Setsecuritymanager (newrmisecuritymanager());

Try {

Perfecttime pt = new perfecttime ();

naming. Bind ("//toad:2005/perfecttime",pt);

System. out. println ("ready to Do time");

} Catch (Exceptione) {

e. Printstacktrace ();

}

}

}/// :~

Here, main () controls all the details of setting up the server. When you save an RMI object, you must take the following actions somewhere in the program:

(1) Create and install a security manager to support RMI. As part of the Java distribution package, the only one for RMI is Rmisecuritymanager.

(2) Create one or more instances of the remote object. Here, you can see that the Perfecttime object was created.

(3) Register at least one remote object to the RMI remote object registry. A method owned by a remote object can generate a handle to another remote object. This allows the customer to access the first remote object only once in the registration table.

1. Setting up the Registry

Here, you can see a call to the static method Naming.bind (). However, this call requires the registry to run as a separate process on the computer. The name of the registry server is Rmiregistry. In a 32-bit Windows environment, you can use:

Start Rmiregistry

Make it run in the background. In Unix, use:

Rmiregistry &

Like many network programs, Rmiregistry is located at an IP address where the machine starts, but it must also monitor a port. If you call Rmiregistry as above and do not use parameters, the port of the registry will default to 1099. If you want it to be on a different port, simply add a parameter to the command line and specify that port number. For this example, the port will be at 2005, so Rmiregistry should start as follows (for 32-bit Windows):

Start Rmiregistry 2005 ( also used by toads)

For UNIX, use the following command:

Rmiregistry 2005 &

Port-related information must be routed to the bind () command, along with the IP address of the machine where the registry resides. But if we want to test the RMI program locally, as the network program in this chapter has been testing, this can be problematic. In JDK 1.1.1, the following two issues exist:

(1) localhost cannot work with RMI. So in order to perform the RMI test on a single machine, the machine name must be provided. To investigate the name of your machine in a 32-bit Windows environment, go to the Control Panel, select "Network", and select the "Identification" card, which lists the computer's name. In my own case, my machine is called "Toad". It appears that the uppercase form is ignored.

(2) RMI does not work unless the computer has an active TCP/IP connection, even if all components only need to communicate with each other on the local machine. This means that you must connect to your ISP (Internet service providers) before attempting to run the program, or you will get some ambiguous offending messages.

With these factors in mind, the bind () command turns out to look like this:

Naming.bind ("//toad:2005/perfecttime", PT);

If you use the default port of 1099, there is no need to specify a port, so you can use:

Naming.bind ("//toad/perfecttime", PT);

In future versions of the JDK (after 1.1), once the problem of localhost has been corrected, local testing can be done normally, with the IP address removed, using only identifiers:

Naming.bind ("Perfecttime", PT);

The service name is arbitrary; it happens to be perfecttime here, just like the class name, but you can modify it as appropriate. The most important thing is to make sure that it is a unique name in the registration table so that the client can get the remote object normally. If the name is already in the registration table, you will get a alreadyboundexception violation. To prevent this problem, consider sticking with rebind () and discarding bind (). This is because rebind () either adds a new entry or replaces the entry with the same name. Although main () exits, our object has been created and registered, so it is kept alive by the registry, waiting for the customer to arrive and make a request for it. As long as the rmiregistry is running, and we don't call the Naming.unbind () method for the name, the object must be in that place. For this reason, when we design our own code, we need to first close rmiregistry and restart it when compiling a new version of the remote object.

It is not always important to start rmiregistry as an external process. If you know beforehand that you are the only application that requires a registry, you can start it inside the program using the following code:

Locateregistry.createregistry (2005);

As before, 2005 represents the port number we chose in this example. This is equivalent to executing rmiregistry 2005 at the command line. However, this approach is often more convenient when designing RMI code because it cancels the extra steps required to start and abort the registry. Once this code is executed, you can use naming to "bind"--bind () as before.

3 Creating roots and dry

If the Perfecttime.java is compiled and run, it will not work even if the rmiregistry is running correctly. This is because the RMI framework is not yet in place. You must first create the root and dry to provide network connection operations and allow us to disguise the remote object as a local object within our own machine. All this behind-the-scenes work is quite complicated. Any object that we pass in and out from a remote object must be "implement Serializable" (if you want to pass a remote reference, not an entire object, the object's parameters can be "implement remote"). It is therefore conceivable that the Gang will automatically serialize and reassemble the data when it "gathers" all parameters and returns results over the network. Fortunately, there is no need to know any details about these aspects, but Gang must be created. One simple process is to call rmic in the compiled code, which will create some of the necessary files. So the only thing to do is to add a new step to the compilation process.

However, the Rmic tool is very much associated with a particular package and classpath. Perfecttime.java is located in Package C15. Ptime, even if we call rmic,rmic in the same directory as Perfecttime.class, the file cannot be found. This is because it searches for a classpath. Therefore, we must specify the classpath at the same time, as follows:

Rmic C15. Ptime.perfecttime

When this command is executed, it does not have to be in the directory containing the Perfecttime.class, but the result is placed in the current directory.

If the rmic runs successfully, there will be two more new classes in the directory:

Perfecttime_stub.class

Perfecttime_skel.class

They correspond to root (Stub) and Dry (Skeleton) respectively. Now we are ready to have the server communicate with the customer.

4 Using Remote objects

The whole purpose of RMI is to simplify the use of remote objects as much as possible. The only additional thing we need to do in our client program is to find and retrieve the remote interface from the server. Since then, the rest is plain Java programming: sending messages to objects. Here are the programs that use Perfecttime:

4.1 Code

import java.rmi.*;

Import java.rmi.registry. *;

Public class Displayperfecttime {

Public staticvoidmain (string[]args) {

System. Setsecuritymanager (newrmisecuritymanager());

Try {

Perfecttimei t = (perfecttimei) naming. Lookup ("//127.0.0.1:2005/perfecttime");

for (inti = 0; I < 10; I+ +)

System. out. println ("Perfect time ="+t. Getperfecttime ());

} Catch (Exceptione) {

e. Printstacktrace ();

}

}

} /// :~

The ID string is the same as the string that is registered with naming, and the first part indicates the URL and port number. Since we are going to use a URL, we can also specify a machine on the Internet.

The return from Naming.lookup () must be styled to the remote interface, not to the class. If you swap a class, you get a violation prompt.

In the following method call:

T.getperfecttime ()

We can see that once a handle to a remote object is obtained, programming with it is very similar to programming with local objects (there is only one difference: The remote method "throws" a remoteexception violation).

5 Alternative for R M I

RMI is just a way to create special objects that can be published over the network. Its greatest advantage is that it provides a "pure Java" solution, but if there are already many code written in other languages, RMI may not be able to meet our requirements. Currently, two of the most competitive alternatives are Microsoft's DCOM (which, according to Microsoft's plan, will eventually be ported to platforms other than Windows) and CORBA. The CORBA self-Java1.1 is a new design concept for cross-platform applications. In the book "Client/server Programming Withjava and CORBA", written by Orfali and Harkey (published by John Wiley&sons in 1997), you get access to Java A comprehensive introduction to distributed objects in (the book seems to be biased towards CORBA). A book that gives a fairer treatment to CORBA is "Java programming with CORBA", written by Andreas Vogel and Keith Duddy, published in 1997.

6 Summary

There are many other concepts that involve networking. Java also provides quite comprehensive support for URLs, including protocol controllers for different types of customers on the Internet, and so on. In addition, a technology that is becoming popular is called a servlet Server. It is an Internet server application that controls customer requests through Java rather than using the previously slow and cumbersome CGI (Common Gateway Interface) protocol. This means that in order to serve at the end of the server, we can program in Java without having to use other languages that we are unfamiliar with. Because Java has excellent porting capabilities, you don't have to worry about what the platform is for hosting this server.

All of these and other features are described in detail in the Java Network programming book. The book was authored by Elliotterustyharold, and O ' Reilly was published in 1997.

74.JAVA Programming Ideas--remote methods

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.