Java RMI and. Net remoting

Source: Internet
Author: User
Java RMI and. Net remoting

Java and. NET provides remote processing functions, but not completely the same. java remote processing is implemented through a "shared interface. net can be implemented through a "shared command set. The two methods are described below.

Java remote processing

Java remote method call (RMI) provides the remote communication function of the Java programming language. This feature allows a program running on the client to call objects on the remote server, this allows Java programmers to distribute operations in the network environment.
To create a simple Java Distributed Remote Method calling program, follow these steps,

1. Define remote interfaces:
In Java, remote objects are instances of classes that implement remote interfaces. remote interfaces declare each method to be called remotely. When you need to create a remote object, you can pass an interface to hide implementation details at the grassroots level. You can send messages through the interface handle.
Remote interfaces have the following features:
1) the remote interface must be public. Otherwise, if the client and remote interface are in the same package, an error is returned when you try to mount a remote object that implements the remote interface.
2) the remote interface must be extended to Java. RMI. Remote.
3) except for exceptions specific to the application, every method in the remote interface must declare java. RMI. RemoteException in its throws clause. (Or the RemoteException parent class ).
4) A remote object passed as a parameter or return value (whether directly or embedded in a local object) must be declared as a remote interface, rather than an implementation class.
The following is the definition of remote interface rmisample.

Import java. RMI .*;
Public interface rmisample extends remote {
Public int sum (int A, int B) throws RemoteException;
}

2. implement remote interfaces:
The remote object implementation class must extend the remote object java. RMI. unicastremoteobject class and implement the defined remote interface. The remote object implementation class contains the code that implements the remote method specified by each remote interface. This class can also contain additional methods, but the customer can only use methods in the remote interface. Because the customer points to a handle of the interface, rather than the class of the interface. You must define a constructor for a remote object. You can use it to call a base class constructor even if you only want to define a default constructor. Because the basic class constructor may throw java. RMI. RemoteException, the exception of Java. RMI. RemoteException must be thrown even if it is not used.
The declaration of remote object implementation class is as follows:

Import java. RMI .*;
Import java. RMI. server .*;
Public class rmisampleimpl extends unicastremoteobject
Implements rmisample {
Rmisampleimpl () throws RemoteException {
Super ();
}
Public int sum (int A, int B) throws RemoteException {
Return A + B;
}
}

Iii. Write server classes:
The class containing the main method can be the implementation class itself, or it can be completely another class. The following uses rmisampleserver to create an instance of a remote object and uses Java. RMI. registry. the createregistry method of the locateregistry class starts the registration service program from the specified port number. You can also run the rmiregistry command to start the registration service program. The default running port of the registration service program is 1099. The remote object name must be bound to the reference to the remote object: naming. rebind ("// localhost: 8808/sample-server", server );
The following is the server class declaration:

Import java. RMI .*;
Import java. RMI. Registry .*;
Public class rmisampleserver {
Public static void main (string ARGs []) {
Try {
Locateregistry. createregistry (8808 );
Sampleserverimpl Server = new sampleserverimpl ();
// Bind the object instance with the name "Sample-server"
Naming. rebind ("// localhost: 8808/sample-server", server );
} Catch (java.net. malformedurlexception me ){
System. Out. println ("malformed URL:" + me. tostring ());
} Catch (RemoteException re ){
System. Out. println ("remote exception:" + RE. tostring ());
}
}
}

4. Compile a client class using remote services:
There are two main functions of the client class: one is to construct the stub program instance of the registration service program through the naming. lookup method, and the other is to call the remote method on the remote object of the server.
The following is the server class declaration:

Import java. RMI .*;
Import java. RMI. server .*;
Public class rmisampleclient {
Public static void main (string [] ARGs)
{
Try {
String url = "// localhost: 8808/sample-server ";
Rmisample rmiobject = (rmisample) Naming. Lookup (URL );
System. Out. println ("1 + 2 =" + rmiobject. sum (1, 2 ));
} Catch (RemoteException exc ){
System. Out. println ("error in lookup:" + exc. tostring ());
} Catch (java.net. malformedurlexception exc ){
System. Out. println ("malformed URL:" + exc. tostring ());
} Catch (Java. RMI. notboundexception exc ){
System. Out. println ("notbound:" + exc. tostring ());
}
}
}

5. Compile the Code:
To compile the Java source file, run the javac command:
Javac rmisample. Java rmisampleimpl. Java rmisampleserver. Java rmisampleclient. Java

6. Create root and stem for remote object implementation:
To create a stub program and a skeleton file, run the rmic compiler with the full name of the compiled class package that contains remote object implementation.
Stub is the proxy of a remote object on the client. It passes the RMI call to the server-side skeleton (skeleton). The latter is responsible for passing the call to the actual remote method as follows:
D:/RMI> rmic-d:/RMI rmisampleimpl execute this command. If rmic runs successfully, there will be two new classes in the RMI directory: rmisampleimpl_stub.class rmisampleimpl_skel.class they correspond to the stub and skeleton respectively ).

7. Run the Code:
Run the server program: in windows, run the following command to start the rmisampleserver program in the background:
D:/RMI> JAVA rmisampleserver
Run the client program:
D:/RMI> JAVA rmisampleclient
Client output: 1 + 2 = 3

. NET remote processing.

Microsoft. net remoting provides a framework that allows an object to interact with another object through the application domain ,. net remoting objects are very suitable for accessing resources through the network without the need to deal with the problems brought about by soap-based WebServices. The following describes how to create a simple. Net remoting Distributed Remote Method calling program.

Step 1: create a shared Remote Object

Create a C # library and name it remoteobject. This will create a "shared command set" for communication between our. NET remote client and the server ".
Public class remoteobject: system. externalbyrefobject
{
Public remoteobject ()
{
System. Console. writeline ("New referance added! ");
}

Public int sum (int A, int B)
{
Return A + B;
}
}
Namespace is required by the object. Remember, if you get system. runtime. remoting. channels. the TCP namespace does not exist. Check whether the system is added as the code above. runtime. remoting. DLL reference.
 
Using system;
Using system. runtime;

The namespace used for the object is remotesample, and the following object is delealbyrefobject. In the namespace, we create a reference and include server operations to complete all the required work.

Namespace remotesample
{
Public class remoteobject: system. externalbyrefobject
{
Public remoteobject ()
{
System. Console. writeline ("New referance added! ");
}

Public int sum (int A, int B)
{
Return A + B;
}
}
} // The remotesample namespace is over

Save the file and name it remoteobject. CS.
Use the command line CSC/T: Library remoteobject. CS to compile the file, you will get a remoteobject. dll file, and you can use it in compiling other C # files.


Step 2: Create a Server Object

Create a Server Object and name it remoteserver. When creating a server object, you must perform the following operations:

1) construct a server channel.
Tcpserverchannel is. net remoting supports one of the two channel types, which can be set as an object to respond to requests from which port, channelservices. registerchannel binds the port number to the TCP/IP stack in the operating system.

Tcpserverchannel channel = new tcpserverchannels (8808 );
Channelservices. registerchannel (Channel );

You can also set it to another channel type HTTP, as long as you simply replace it with the httpserverchannel object in the system. runtime. remoting. channels. Http namespace. The difference between using HTTP and TCP channels is that if an application runs on a LAN, it is better to use the TCP channel because it has better performance than the HTTP channel; if an application runs on the internet, HTTP is the only option based on the firewall configuration. Remember that if the firewall software is used, the Firewall should be configured to allow TCP data traffic to pass through the port you selected for the object.

2) register the object type on the server as a known type.
Remotingconfiguration. registerwellknownservicetype (typeof (remoteobject ),
"Remoteobject", wellknownobjectmode. singlecall );
This line of code sets some parameters in the service and binds the name of the target object to a remote object. The first parameter is the bound object, the second parameter is the string of the remote object name in the TCP or HTTP channel. The third parameter tells the container how to process the object when a request to the object is sent. Although wellknownobjectmode. singlecall uses an object instance for all callers, it generates an instance of this object for each customer. If wellknownobjectmode. singlecall is used, each incoming message is provided by the same object instance.

The complete object code is as follows:
Using system; using system. runtime;
Using system. runtime. remoting;
Using system. runtime. remoting. channels;
Using system. runtime. remoting. channels. TCP;
Using remotesample;
Namespace remotesampleserver
{
Public class remoteserver
{
Public static void main (string [] ARGs)
{
Tcpserverchannel channel = new tcpserverchannels (8808 );
Channelservices. registerchannel (Channel );
Remotingconfiguration. registerwellknownservicetype (typeof (remoteobject ),
"Remoteobject", wellknownobjectmode. singlecall );
System. Console. writeline ("press any key ");
System. Console. Readline ();
}
}
}
Save the file and name it remoteserver. CS.
Use the command line CSC/R: system. runtime. remoting. dll/R: remoteobject. dll remoteserver. CS to compile the remoteserver. EXE file generated by this program.


Step 3: Create a remote client program
Create a Server Object and name it remoteclient. A tcp client channel is created when a server object is created. The channel is not bound to a port, and a remote remoteobject object reference is obtained. The activator. GetObject method returns an object type value, which is then assigned to remoteobject. The parameters we pass to it are very similar to the parameters passed to remotingconfiguration in the server object. The first parameter is of the object type, and the second parameter is the URI of the remote object.

Channelservices. registerchannel (New tcpclientchannel ());
Remoteobject remoteobj = (remoteobject) activator. GetObject (typeof (remoteobject ),
"TCP: // localhost: 8808/remoteobject ");

The remoteclient code is as follows:

Using system;
Using system. runtime. remoting;
Using system. runtime. remoting. channels;
Using system. runtime. remoting. channels. TCP;
Using remotesample;
Namespace remotesampleclient
{
Public class remoteclient
{
Public static void main (string [] ARGs)
{
Channelservices. registerchannel (New tcpclientchannel ());
Remoteobject remoteobj = (remoteobject) activator. GetObject (typeof (remoteobject ),
"TCP: // localhost: 8808/remoteobject ");
Console. writeline ("1 + 2 =" + remoteobj. sum (1, 2). tostring ());
Console. Readline (); // do not close the window until the result is displayed.
}

}
}

Save the file and name it remoteclient. CS.
Use the command line CSC/R: system. runtime. remoting. dll/R: remoteobject. dll remoteclient. CS to compile the remoteclient. EXE file generated by this program.


Step 4: Test
Run server.exein windows, and then run client.exe in another window.
If everything works properly, the client outputs: 1 + 2 = 3.


It can be seen that net remoting does not need to create a stub program and a skeleton file. It is easier to use than Java's RMI, and provides an excellent way to process resources in the LAN or even the Internet, RMI is more widely used than Java.

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.