Ice simple introduction and use example

Source: Internet
Author: User
Tags getmessage object object serialization

1, ice is what.
Ice is Zeroc's Open source communications protocol product, its full name is: The Internet Communications Engine, translated into Chinese is the Internet communication Engine, is an object-oriented middleware, so that we can build a distributed application at the lowest cost. Ice allows us to focus on the development of the application logic, which handles all the underlying network interface programming, so that we don't have to consider the details: turn on the network connection, the serialization and deserialization of network data transmission, the number of attempts to connect failed.

2, why there are ice.
Ice is a good solution for distributed applications, although there are some more popular distributed application solutions, such as Microsoft. NET (and the original DCOM), CORBA and Web service, etc., but these object-oriented middleware have some deficiencies:
. NET is a Microsoft product, only for Windows system, and the real situation is that in the current network environment, different computers will run different systems, such as Linux can not use the above. NET;
Although CORBA does a lot of work on unified standards, there is still a lack of interoperability between different vendor implementations, and no vendor can provide all the implementation support for all heterogeneous environments, and the implementation of CORBA is more complex, and the cost of learning and implementation is higher;
The worst drawback of web service is his performance problem, which is rarely considered for Web service in highly demanding industries.
The creation of ice stems from the lack of middleware for. NET, CORBA, and Web service, which can support different systems, such as Windows, Linux, etc., and can be used in a variety of development languages, such as C + +, C, JAVA, RUBY, PYTHON, VB, etc. , the server can be mentioned in any of the above language implementation, the client can also be based on their own actual situation to choose different language implementations, such as the server with the implementation of the C language, and the client adopts the Java language, the underlying communication logic through the ice encapsulation implementation, we need to focus on business logic.

3, how the ice is working.
Ice is an object-oriented middleware platform, which means that ice provides tools, APIs, and library support for building object-oriented client-server applications. To communicate with an object held by ice, the client must hold the proxy for this object (which is the same as the CORBA reference), where the proxy refers to an instance of the object, which the ice locates at runtime, then searches for or activates it, and then passes the in parameter to the remote object. The return result is obtained again through the out parameter.
The agents mentioned here are divided into direct proxies and indirect proxies, which directly represent the identity of an object and the running address of its server; the indirect proxy refers to the identity of an object that is stored internally, and the object adapter name (objects adapter name). The indirect proxy does not contain addressing information, and in order to locate the server correctly, the client at runtime uses the object adapter name inside the proxy to pass it to a locator service, such as the Icepack service, and then the locator looks up the adapter name as a keyword in the table containing the server address. To return the current server address to the customer, client run time now knows how to contact the server, and will Dispatch (dispatch) customer requests as usual.
Ice can be guaranteed in any network environment or operating system, the success of the call only once, it will try to navigate to the remote server, in the case of connection failure will do a trial repetitive connection, do not even the situation will give users a hint.
When the client invokes a method on the server, can be implemented synchronously or asynchronously, and synchronous calls are the same as calling their own local methods, and other behaviors are blocked; asynchronous invocation is a very useful way to invoke, such as the data the server needs to prepare from other asynchronous interfaces, at which point the client does not have to wait. When the service-side data is ready and the client is notified by message, the server can do other things, and the client can get the data from the server.

4, Ice call mode
ICE uses the network protocol has TCP, UDP and SSL three kinds, differs from webservice,ice in the invocation pattern to have several kinds of options, and each kind of scheme is making the corresponding choice to the different network protocol characteristic.
OneWay (One-way call): the client simply registers the call to the local transport buffer (the transport buffers) immediately after returning, does not wait for the return of the call result, is not responsible for the result of the call.
TwoWay (bidirectional invocation): The most common mode, synchronous method invocation mode, can only use TCP or SSL protocol.
Datagram (Datagram): Similar to a oneway call, the difference is that a Datagram call can only take a UDP protocol and only a method that has no return value and no output parameter can be invoked.
Batchoneway (Batch one-way call): First the call exists within the call buffer, to a certain limit after the automatic bulk send all requests (also can manually brush the buffer).
Batchdatagram (Bulk Datagram): similar to above.
Different invocation patterns in fact correspond to the fixed business, for most of the return value or need real-time response method, we may all adopt TwoWay method, for some no return value or do not rely on return value of the business, we can use OneWay or Batchoneway way, For example, message notifications, and the rest of the datagram and Batchdatagram methods are typically used for businesses with no return value and no reliability checks, such as logs.

5, client and service-side structure

This diagram shows the use of ice as a middleware platform, client and server applications are composed of the application code and Ice Library code mix.
Customer application and server application are the client and service side respectively.
The agent is implemented according to the ice file defined by slice, which provides a down-call interface that provides serialization and deserialization of the data.
The core part of Ice provides the core communication functions such as the network connection between client and server, as well as the implementation of other network communication functions and possible problems, so that we should not pay attention to this piece while writing the application code, and focus on the realization of application function.

6, a simple example of ice
To use ice, you must first install ice, installation and configuration references are as follows:
Windows:http://blog.csdn.net/fenglibing/archive/2011/04/28/6368665.aspx
LINUX (BDB installation is still problematic, unable to use Slice2java): http://blog.csdn.net/fenglibing/archive/2011/04/27/6367559.aspx
This example is a Java example, extracted from the help documentation for ICE, a test program that outputs Hello World, with an ice version of 3.1.1.
1, the preparation of an ice file and named: Printer.ice, its contents are:

Module Demo {interface Printer {void printstring (string s);};

2, go to command line, save directory Execution command in Printer.ice file:
Slice2java Printer.ice
A demo folder will be generated under the directory, which will generate some Java files, as shown here:

3), the class diagram structure of these files is as follows:

Here are some of the generated files to explain, divided into 22 parts, server-side class files and client class files:
<interface-name>.java
This source file declares the Java interface for the interface name set in the ice file, as here is printer.
_<interface-name>operations.java
_<interface-name>operationsnc.java
This is the interface file for two definition operations, each interface file defines an operation implementation, the defined operation is consistent with the operation defined in the slice interface, but the method defined in _<interface-name>operations.java is one more parameter. Ice.current __current "(Note: the definition of the current object, see the 31.6 the Ice::current object description in the 3.1.1 version of the document), is a parameter that allows us to access" executing requests "and" The implementation of the operation in the server "and other information, that is, our request needs the support of other requests or to obtain the execution results of other requests, we can call this method, both interface files will be inherited by the interface file _<interface-name>.java.
_<interface-name>disp.java This file contains the definition of the server-side skeleton class, and the interface definition used to inherit this object, where the interface refers the interface that the client invokes.
The <interface-name>prxholder.java Proxy defines the holder class, which is used for the out parameter. General parameters are value-passing, which is the function of making arguments pass by reference. The ice framework uses a number of reflection mechanisms, which are a mapping for changing remote parameters.

_<interface-name>del.java
_<interface-name>deld.java
_<interface-name>delm.java
Don't worry about these files, which contain code for use within the Java map; they contain features that are not relevant to the application.
<interface-name>prx.java This is the proxy interface. For example Printerprx, in the customer's address space, the PRINTERPRX instance is the "local ambassador" of "instance of the printer interface in a remote server". All the details related to the server-side object, such as its address, the protocol used, and the identity of the object, are encapsulated in the instance.
Note that printerprx inherits from Ice.objectprx. This reflects the fact that all ice interfaces are implicitly inherited from Ice::object.
To be more clear, the method calls for this class are all calls to the remote server, and the implementation of the Printstring () method is implemented on the remote server side.
<interface-name>prxhelper.java This is the interface of the Proxy definition helper class, is to help you get the proxy class. Checkedcast and Uncheckedcast are commonly used in two methods. Both of these methods implement a downward conversion.
Note that Checkedcast will contact the server. This is necessary because only the proxy implementation in the server case knows exactly what type of object it is. Therefore, Checkedcast may throw connecttimeoutexception or objectnotexistexception (This also explains why the helper class is needed: Ice must contact the server at run time, so we cannot use Java Downward conversion).
In contrast, Uncheckedcast does not contact the server, but instead unconditionally returns the agent with the requested type. However, if you are using Uncheckedcast, you must be sure that the agent really supports the type you want to convert to, and if you are mistaken, you are likely to throw a Run-time exception when you invoke an action on the proxy. For such a mismatch of types, it may eventually cause operationnotexistexception, but it may also cause other exceptions, such as a compilation exception. Also, if an object happens to have an operation with the same name, but the parameter type is different, it is possible that there is no exception at all, and you end up sending the call to an object of the wrong type; The object may be doing something very bad.

4, create an Eclipse project, copy the generated files to the SRC directory, and import Ice.jar in Classpath.
5), set up three test Java files, Server.java, Printeri.java and Client.java:
Printeri.java is the implementation of the Skeleton class _printerdisp on the server, returning the Printeri.java object to the client, where the function is to directly output the string parameter passed in:

public class Printeri extends Demo._printerdisp {public void printstring (String s, ice.current current) {System.out.prin TLN (s); } }

Server.java is a service-side service agent that receives client requests for action:

Public class Server {public static void main (string[] args) {int status = 0; Ice.communicator IC = null; try {//first-make connection, args can pass some first-order parameters, such as connection timeout, the initial number of the client connection pool IC = Ice.Util.initialize (args);//Create an adapter named Simpleprinteradapter. The adapter is required to use the default protocol (TCP/IP listening port is 10000 request) Ice.objectadapter adapter = ic.createobjectadapterwithendpoints (" Simpleprinteradapter "," default-p 10000 "); Instantiate a Printeri object and create a service object for the printer interface Ice.object object = new Printeri (); Adds a service unit to the adapter and assigns the service object the name Simpleprinter, which is used to uniquely determine a service unit Adapter.add (object, Ice.Util.stringToIdentity (" Simpleprinter ")); The advantage of activating the adapter is that you can wait until all resources are in place to trigger the adapter.activate (); Let the service continue to monitor the request Ic.waitforshutdown () before exiting; catch (Ice.localexception e) {e.printstacktrace (); status = 1;} catch (Exception e) {System.err.println e.getmessage ( )); status = 1; } if (IC!= null) {//clean up//try {Ic.destroy ();} catch (Exception e) {System.err.println (E.getmessage ()); status = 1; } system.exit (status); } }

Client.java is the client code that initiates the request to the server and operates the returned proxy object:

public class Client {public static void main (string[] args) {int status = 0; Ice.communicator IC = null; try {//first-made ICS = Ice.Util.initialize (args);//Incoming remote service unit name, network protocol, IP and port, get printer Remote agent, the Stringtoproxy method used here Ice.objectprx base = Ic.stringtoproxy ("simpleprinter:default-p 10000"); By Checkedcast down, gets the remote of the printer interface, detects whether the service unit obtained by the incoming name printer the proxy interface, and if not, returns the null object DEMO.PRINTERPRX printer = Demo.PrinterPrxHelper.checkedCast (base); if (printer = = null) throw new Error ("Invalid proxy"); Pass the Hello world to the service side and let the server print, because this method will eventually execute printer.printstring on the server ("Hello world!"); catch (Ice.localexception e) {e.printstacktrace (); status = 1;} catch (Exception e) {System.err.println e.getmessage ( )); status = 1; } if (IC!= null) {//clean up//try {Ic.destroy ();} catch (Exception e) {System.err.println (E.getmessage ()); status = 1; } system.exit (status); } }

6), running the client and service side
Running server-side: Java Server
Running clients: Java client
Let's see the effect.

7, the performance and efficiency of ice
Ice performance is relatively good, because his own transmission mechanism is based on the binary system, someone on the internet has done performance testing, evaluation is better, I have not done performance testing, the current judgment is based on network data, please read the following article:
High Performance computing-ice performance test
The advantages of ice and CORBA comparison

8, the advantages of ice
Support synchronous and asynchronous message delivery;
supports multiple interfaces;
Machine-Independent, customers and servers are shielded from the underlying machine architecture. For the application code, problems like byte-order and padding are hidden;
Language independence, customers and servers can be deployed separately, the language can also be different;
Implementation-Independent, the customer does not know how the server implements its object. This means that the implementation of the server can change after the customer is deployed;
Os Independent, the Ice API is completely portable, so the same source code can be used in Windows and UNIX
Compile and run on;
Thread support, Ice run time is completely threaded, its APIs are thread-safe, and as an application developer, (in addition to synchronizing when accessing shared data), there is no need to make extra effort to develop threaded high-performance customers and servers.
The transport mechanism is independent, and ICE currently uses TCP/IP and UDP as the transport protocol. Neither the client nor the server code needs to know the underlying transport mechanism;
Location and server transparency, Ice run time is responsible for locating objects and managing the underlying transport mechanisms, such as opening and closing connections;
Security, SSL strong encryption allows customers and servers to communicate completely securely, so that applications can use unsecured network to communicate securely, you can use glacier through the firewall, the implementation of secure request forwarding, and fully support the callback;
Built-in persistence mechanism, using Freeze, creating a lasting object implementation becomes a very easy thing, ICE provides built-in support for high-performance database Berkeley db[18];
Open source.

Postscript
Here is a simple introduction to ice, there are many things not mentioned, such as ice syntax rules, ice version Control (FACET), persistence (feeze), Service Boxing Management (icebox), file distribution (ICEPATCH2), publish/Subscribe Service (Icestorm), network topology load solution--Ultimate Weapon (Icegrid), plug-ins that provide SSL with secure transport into Protocol (ICESSL), lightweight Ice Application Firewall solution (GALCIER2), these are left behind to learn.

This article originates from: Feng Libin's blog




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.