浅入ICE组件编程

一、ICE介绍

         ICE是ZeroC公司开发的一款高效的开源中间件平台,全称是Internet Communications Engine。

         它的主要设计目标是:

         • 提供适用于异种环境的面向对象中间件平台。

         • 提供一组完整的特性,支持广泛的领域中的实际的分布式应用的开发。

         • 避免不必要的复杂性,使平台更易于学习和使用。

         • 提供一种在网络带宽、内存使用和 CPU 开销方面都很高效的实现。

         • 提供一种具有内建安全性的实现,使它适用于不安全的公共网络。

         ICE支持多种编程语言:C++、Java、C#、VB、Python、Ruby,也就是说使用ICE时我们可以让这些语言无缝沟通,不过由于ICE是用C++编写的,不管用什么语言,你都需要先用C++编译出一个ICE才行(或者下载已编译的版本)。

         跨语言的分布式系统首先要定义一个与编程语言无关的接口描述语法,用于分布于各处的服务器与客户端之间对话。比如DCOM和CORBA使用IDL语法,SOAP使用WSDL语法,当然还有时下流行的JSON。ICE使用的是称为Slice(Specificatoin Language for Ice)的语法,Slice语法和C++(或Java,C#)比较相近,只要会C++(或Java,C#)很容易就能写Slice定义了。

二、配置ICE开发环境

         首先,从http://www.zeroc.com/download.html 下载ICE,目前最新版本是Ice-3.5.1。下载页面里除了ICE的源码之外,也提供了VC或C++Builder的已编译安装包以及各Linux版本的RPM下载。

         如果下载的是源码版本,需要编译的话,最好使用相同版本的编译器。

1)、ICE需要一些第三方库,在编译ICE之前要先编译第三方库,清单如下(它们也能在ICE官网上下载):

Berkeley DB

expat

OpenSSL

bzip2

mcpp

2)、编译完上面这些库以后,把它们放到同一个目录中,然后设置用户环境变量。

         ICE_ROOT= D:\Program Files\ZeroC\Ice-3.5.1

3)、把上面编译好或直接下载的已编译版本的ice.lib和iceutil.lib(或Debug版本的iced.lib和 iceutild.lib)链接入项目即可。

三、ICE的“HelloWorld”

         本文以网上用到比较多的printer经典代码作为范例说明。

1)、定义接口文件demo.ice

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //**********************************************************************  
  2.   
  3. //  
  4.   
  5. // Copyright (c) 2014  
  6.   
  7. // xxxxx有限公司  
  8.   
  9. // 2014.05.23  
  10.   
  11. // liuxuezong, 上海  
  12.   
  13. //  
  14.   
  15. // AllRights Reserved  
  16.   
  17. //  
  18.   
  19. //**********************************************************************  
  20.   
  21.    
  22.   
  23. #ifndef demo_ice  
  24.   
  25. #define demo_ice  
  26.   
  27. //  
  28.   
  29. // version 1.0.0  
  30.   
  31. //  
  32.   
  33.    
  34.   
  35. module Demo  
  36.   
  37. {  
  38.   
  39.          interface Printer  
  40.   
  41.          {  
  42.   
  43.               void printString(string strMsg);  
  44.   
  45.          };  
  46.   
  47. };  
  48.   
  49.    
  50.   
  51. #endif  
         它定义一个Printer接口(interface),这个接口只有一个printString方法,输入参数是一个字符串(string)。最后,这个接口位于Demo模块(module)之下。

2)、生成接口文件

         使用slice2cpp程序依据这个Slice定义生成C++使用的头文件和对应的代理代码。

>slice2cpp demo.ice

    如果没提示错误,就会生成demo.h和demo.cpp,把这两个文件加入到服务器端项目和客户端项目后,客户端就可以向服务器发送消息了。

> slice2java demo.ice

    生成java相关代码,文件较多,这里就不一一写出了。

> slice2cs demo.ice

    生成c#相关代码只有一份:demo.cs。

3)、Slice与C++的映射关系

Slice

C++

#include

#include

#ifndef

#ifndef

#define

#define

#endif

#endif

module

namespace

bool

bool

byte

Ice::Byte

short

Ice::Short

int

Ice::Int

long

Ice::Long

float

Ice::Float

double

Ice::Double

string

Ice::string

enum

enum(不支持指定数字)

struct

struct

class

class(所有方法都是纯虚函数)

interface

struct(所有方法都是纯虚函数,没有成员变量)

sequence<T>

std::vector<T>

dictionary<Key,Value>

std::map<Key,Value>

exception Err

class Err:public Ice:UserException

nonmutating方法限定符

const方法

idempotent方法限定符

-

out 参数限定符

引用类型

*

对应类型的代理类

         参考这个表,可以知道上面的Slice定义对应的C++映射如下:

namespace Demo

{

         struct Printer

         {

                   virtual void printString(string strMsg) = 0;

         };

};

4)、C++代码实现

第1步:新建一个控制台项目democlient;

第2步:将“./;$(ICE_ROOT)\include”添加到“c/c++”->“常规”->“附件包含目录” 列表中;


图3-1 包含目录设置

第3步:将“$(ICE_ROOT)\lib” 添加到“链接器”->“常规“->“附件库目录”列表中;


图3-2 附加库目录设置

第4步:将“iced.lib”和“iceutild.lib”(debug版本)添加到“链接器”->“输入“-> “附加依赖项”列表中,链接入到项目中。


图3-3 导入静态库设置

C++客户端代码democlient:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include <ice/ice.h>  
  2.   
  3. #include "demo.h"  
  4.   
  5.    
  6.   
  7. using namespace std;  
  8.   
  9. using namespace Demo;  
  10.   
  11.    
  12.   
  13. int main(int argc, char *argv[])  
  14.   
  15. {  
  16.   
  17.          Ice::CommunicatorPtr ic;  
  18.   
  19.          try  
  20.   
  21.          {  
  22.   
  23.                    // 初始化Ice运行库  
  24.   
  25.                    ic = Ice::initialize(argc,argv);  
  26.   
  27.                    // 在10000端口取得 SimplePrinter代理对象  
  28.   
  29.                    Ice::ObjectPrx base =ic->stringToProxy("SimplePrinter:default -p10000");  
  30.   
  31.                    // 把对象转换成Printer 代理  
  32.   
  33.                    PrinterPrx printer =  PrinterPrx::checkedCast(base);  
  34.   
  35.                    if(!printer)  
  36.   
  37.                    {  
  38.   
  39.                             throw "InvalidProxy!";  
  40.   
  41.                    }  
  42.   
  43.                    // 能够用这个代码调用printString方法  
  44.   
  45.                    printer->printString("Hello World!");  
  46.   
  47.          }  
  48.   
  49.          catch (const Ice::Exception &e)  
  50.   
  51.          {  
  52.   
  53.              cerr << e << endl;  
  54.   
  55.          }  
  56.   
  57.          catch (const char *msg)  
  58.   
  59.          {  
  60.   
  61.               cerr << msg << endl;  
  62.   
  63.          }  
  64.   
  65.          // 回收Ice运行库所用的资源  
  66.   
  67.          if (ic)  
  68.   
  69.          {  
  70.   
  71.                    ic->destroy();  
  72.   
  73.          }  
  74.   
  75.          return0;  
  76.   
  77. }  
        您也可以把服务器端部署到别的电脑上,客户端代码改成如下代码,即可实现远程调用。

        Ice::ObjectPrx base =ic->stringToProxy("SimplePrinter:default -h 127.0.0.1 -p 10000")

C++服务器代码demoserver:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include "demo.h"  
  2.   
  3.    
  4.   
  5. using namespace std;  
  6.   
  7. using namespace Demo;  
  8.   
  9.    
  10.   
  11. // 实现printString方法  
  12.   
  13. struct CPrinterImp : Printer  
  14.   
  15. {  
  16.   
  17.          virtual void printString(const::std::string& strMsg,  
  18.   
  19.                    const::Ice::Current& = ::Ice::Current())  
  20.   
  21.          {  
  22.   
  23.               cout << strMsg << endl;    
  24.   
  25.          }  
  26.   
  27. };  
  28.   
  29.    
  30.   
  31. int main(int argc, char *argv[])  
  32.   
  33. {  
  34.   
  35.          Ice::CommunicatorPtr ic;  
  36.   
  37.    
  38.   
  39.          try  
  40.   
  41.          {  
  42.   
  43.                    // 回收Ice运行库所用的资源  
  44.   
  45.                    ic = Ice::initialize(argc,argv);  
  46.   
  47.                    // 建立ObjectAdapter,命名为SimplePrinterAdapter,使用默认协议一般是tcp并在10000端口监听。  
  48.   
  49.                    Ice::ObjectAdapterPtr adapter= ic->createObjectAdapterWithEndpoints(  
  50.   
  51.                             "SimplePrinterAdapter""default -p 10000");  
  52.   
  53.                    // 把我们实现的Printer加入ObjectAdapter,并命名为SimplePrinter  
  54.   
  55.                    Ice::ObjectPtr object = new CPrinterImp;  
  56.   
  57.                    adapter->add(object,ic->stringToIdentity("SimplePrinter"));  
  58.   
  59.                    adapter->activate();  
  60.   
  61.                    // 等待直到Communicator关闭  
  62.   
  63.                    ic->waitForShutdown();  
  64.   
  65.          }  
  66.   
  67.          catch (const Ice::Exception &e)  
  68.   
  69.          {  
  70.   
  71.                    cerr << e <<endl;  
  72.   
  73.          }  
  74.   
  75.          catch (const char *msg)  
  76.   
  77.          {  
  78.   
  79.                    cerr << msg <<endl;  
  80.   
  81.          }  
  82.   
  83.          // 回收Ice运行库所用的资源  
  84.   
  85.          if (ic)  
  86.   
  87.          {  
  88.   
  89.                    ic->destroy();  
  90.   
  91.          }  
  92.   
  93.          return0;  
  94.   
  95. }  
         以上代码编译通过后,启动服务端程序。每次调用客户端后,服务器端会显示一行

         “Hello World!”

5)、java代码实现


图3-4 设置ice.jar

    从iec3.5.1的lib文件中,把ice.jar添加到工程jar目录中。

java客户端代码democlient:

democlient.java主程序:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public class democlient  
  2.   
  3. {  
  4.   
  5.     public static void main(String[] args)  
  6.   
  7.     {  
  8.   
  9.         int status = 0;  
  10.   
  11.         Ice.Communicator ic = null;  
  12.   
  13.         try  
  14.   
  15.         {  
  16.   
  17.             // Initialize ICE  
  18.   
  19.             ic = Ice.Util.initialize(args);  
  20.   
  21.              
  22.   
  23.             // Ice.ObjectPrxbase = ic.stringToProxy(  
  24.   
  25.             //"SimplePrinter:tcp -h 127.0.0.1 -p 10000");           
  26.   
  27.             Ice.ObjectPrx base = ic.stringToProxy(  
  28.   
  29.                     "SimplePrinter:default-p 10000");  
  30.   
  31.              
  32.   
  33.             Demo.PrinterPrx printer = Demo.PrinterPrxHelper.checkedCast(base);  
  34.   
  35.              
  36.   
  37.             if (printer == null)  
  38.   
  39.             {  
  40.   
  41.                 thrownew Error("Invalidproxy");  
  42.   
  43.             }  
  44.   
  45.              
  46.   
  47.             printer.printString("Hello World!");  
  48.   
  49.         }        
  50.   
  51.         catch (Ice.LocalException ex)  
  52.   
  53.         {  
  54.   
  55.             ex.printStackTrace();  
  56.   
  57.             status = 1;  
  58.   
  59.         }  
  60.   
  61.         catch (Exception e)  
  62.   
  63.         {  
  64.   
  65.             System.err.println(e.getMessage());  
  66.   
  67.             status = 1;  
  68.   
  69.         }  
  70.   
  71.         if (ic != null)  
  72.   
  73.         {  
  74.   
  75.             try  
  76.   
  77.             {  
  78.   
  79.                 ic.destroy();  
  80.   
  81.             }  
  82.   
  83.             catch (Exception e)  
  84.   
  85.             {  
  86.   
  87.                 System.err.println(e.getMessage());  
  88.   
  89.                 status = 1;  
  90.   
  91.             }  
  92.   
  93.         }  
  94.   
  95.         System.exit(status);  
  96.   
  97.     }  
  98.   
  99. }  

java服务端代码demoserver:

PrinterImp.java接口实现:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public class PrinterImp extends Demo._PrinterDisp  
  2.   
  3. {  
  4.   
  5.     private static final long serialVersionUID = 1L;  
  6.   
  7.    
  8.   
  9.     public void printString(String strMsg, Ice.Current current)  
  10.   
  11.     {  
  12.   
  13.          System.out.println(strMsg);  
  14.   
  15.     }  
  16.   
  17. }  

demoserver.java主程序:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public class demoserver  
  2.   
  3. {  
  4.   
  5.     public static void main(String[] args)  
  6.   
  7.     {  
  8.   
  9.         int status = 0;  
  10.   
  11.         Ice.Communicator ic = null;  
  12.   
  13.         try  
  14.   
  15.         {  
  16.   
  17.             // Initialize ICE  
  18.   
  19.             ic = Ice.Util.initialize(args);  
  20.   
  21.              
  22.   
  23.             // Create anobject adapter, which listens on port 1000, using TCP/IP.  
  24.   
  25.             Ice.ObjectAdapter adapter =ic.createObjectAdapterWithEndpoints(  
  26.   
  27.                     "SimplePrinterAdapter""default -hlocalhost -p 10000");  
  28.   
  29.              
  30.   
  31.             // Create servant(implementation) object.  
  32.   
  33.             Ice.Object object = new PrinterImp();  
  34.   
  35.              
  36.   
  37.             // Add servant tothe object adapter's active servant map.  
  38.   
  39.             adapter.add(object, Ice.Util.stringToIdentity("SimplePrinter"));  
  40.   
  41.              
  42.   
  43.             // Activate theobject adapter.  
  44.   
  45.             adapter.activate();  
  46.   
  47.              
  48.   
  49.             // Just waituntil we're finished.  
  50.   
  51.             ic.waitForShutdown();            
  52.   
  53.         }        
  54.   
  55.         catch (Ice.LocalException ex)  
  56.   
  57.         {  
  58.   
  59.             ex.printStackTrace();  
  60.   
  61.             status = 1;  
  62.   
  63.         }  
  64.   
  65.         catch (Exception e)  
  66.   
  67.         {  
  68.   
  69.             System.err.println(e.getMessage());  
  70.   
  71.             status = 1;  
  72.   
  73.         }  
  74.   
  75.         if (ic != null)  
  76.   
  77.         {  
  78.   
  79.             try  
  80.   
  81.             {  
  82.   
  83.                 ic.destroy();  
  84.   
  85.             }  
  86.   
  87.             catch (Exception e)  
  88.   
  89.             {  
  90.   
  91.                 System.err.println(e.getMessage());  
  92.   
  93.                 status = 1;  
  94.   
  95.             }  
  96.   
  97.         }  
  98.   
  99.         System.exit(status);  
  100.   
  101.     }  
  102.   
  103. }  
        java 服务端的程序需要绑定主机 IP ,否则上述语句如果改成这样:Ice.ObjectAdapteradapter = ic.createObjectAdapterWithEndpoints(

                   "SimplePrinterAdapter","default-p 10000");

         运行demoserver之后,会出现如下错误:

Ice.SocketException

    error = 0

    atIceInternal.Network.doBind(Network.java:251)

    atIceInternal.TcpAcceptor.<init>(TcpAcceptor.java:119)

    atIceInternal.TcpEndpointI.acceptor(TcpEndpointI.java:414)

    atIceInternal.IncomingConnectionFactory.<init>(IncomingConnectionFactory.java:376)

    atIce.ObjectAdapterI.<init>(ObjectAdapterI.java:1028)

    atIceInternal.ObjectAdapterFactory.createObjectAdapter(ObjectAdapterFactory.java:160)

    atIce.CommunicatorI.createObjectAdapterWithEndpoints(CommunicatorI.java:89)

    atdemoserver.main(demoserver.java:12)

Caused by: java.net.SocketException: Address family not supported by protocol family: bind

    atsun.nio.ch.Net.bind(Native Method)

    atsun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:119)

    atsun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:59)

    atIceInternal.Network.doBind(Network.java:245)

    ... 7 more

6)、C#代码实现


图3-5 添加引用库ice

democlient.cs主程序:

[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace democlient  
  7. {  
  8.     class Program  
  9.     {  
  10.         static int Main(string[] args)  
  11.         {  
  12.             int status = 0;  
  13.             Ice.Communicator ic = null;  
  14.             try  
  15.             {  
  16.                 ic = Ice.Util.initialize(ref args);  
  17.                 Ice.ObjectPrx obj = ic.stringToProxy("SimplePrinter:default -h localhost -p 10000");  
  18.                 Demo.PrinterPrx printer = Demo.PrinterPrxHelper.checkedCast(obj);  
  19.                 if (printer == null)  
  20.                 {  
  21.                     throw new ApplicationException("Invalid proxy");  
  22.                 }  
  23.   
  24.                 printer.printString("Hello World!");  
  25.             }              
  26.             catch (Exception e)  
  27.             {  
  28.                 Console.Error.WriteLine(e);  
  29.                 status = 1;  
  30.             }  
  31.             if (ic != null)  
  32.             {  
  33.                 try  
  34.                 {  
  35.                     ic.destroy();  
  36.                 }  
  37.                 catch(Exception e)  
  38.                 {  
  39.                     Console.Error.WriteLine(e);  
  40.                     status = 1;  
  41.                 }  
  42.             }  
  43.             return status;  
  44.         }  
  45.     }  
  46. }  


demoserver.cs主程序:

[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. using System;  
  2.   
  3. using System.Collections.Generic;  
  4.   
  5. using System.Linq;  
  6.   
  7. using System.Text;  
  8.   
  9. using System.Reflection;  
  10.   
  11.    
  12.   
  13. public class PrinterImpl : Demo.PrinterDisp_  
  14.   
  15. {  
  16.   
  17.     public override void printString(string strMsg, Ice.Current current)  
  18.   
  19.     {  
  20.   
  21.         Console.WriteLine(strMsg);  
  22.   
  23.     }  
  24.   
  25. }  
  26.   
  27.    
  28.   
  29. namespace demoserver  
  30.   
  31. {  
  32.   
  33.     class Program  
  34.   
  35.     {  
  36.   
  37.         public static int Main(string[]args)  
  38.   
  39.         {  
  40.   
  41.             intstatus = 0;  
  42.   
  43.             Ice.Communicatoric = null;  
  44.   
  45.             try  
  46.   
  47.             {  
  48.   
  49.                 ic = Ice.Util.initialize(refargs);  
  50.   
  51.                 Ice.ObjectAdapteradapter =  
  52.   
  53.                     ic.createObjectAdapterWithEndpoints("SimplePrinterAdapter""default -h localhost -p 10000");  
  54.   
  55.                 Ice.Objectobj = new PrinterImpl();  
  56.   
  57.                 adapter.add(obj,ic.stringToIdentity("SimplePrinter"));  
  58.   
  59.                 adapter.activate();  
  60.   
  61.                 ic.waitForShutdown();  
  62.   
  63.             }  
  64.   
  65.             catch (Exception e)  
  66.   
  67.             {  
  68.   
  69.                 Console.Error.WriteLine(e);  
  70.   
  71.                 status = 1;  
  72.   
  73.             }  
  74.   
  75.             if (ic != null)  
  76.   
  77.             {  
  78.   
  79.                 try  
  80.   
  81.                 {  
  82.   
  83.                     ic.destroy();  
  84.   
  85.                 }  
  86.   
  87.                 catch (Exception e)  
  88.   
  89.                 {  
  90.   
  91.                     Console.Error.WriteLine(e);  
  92.   
  93.                     status = 1;  
  94.   
  95.                 }  
  96.   
  97.             }  
  98.   
  99.             returnstatus;  
  100.   
  101.         }  
  102.   
  103.     }  
  104.   
  105. }  

四、ICE使用小结

         本文主要从printer经典的例子入手,综合使用三种开发语言,验证ICE在不同语言环境下的使用性如何。从ICE的开发流程上来看,与CORBA开发流程类似。两者的接口文件定义基本相接近。如果您曾经深入接触或开发过CORBA组件软件,那么再入手ICE研究开发工作,将是一件令人愉快的事情,因为它是那么随心所欲—Easy。

         从企业今后部署的经济方面考虑,相对于重量级CORBA中间件组件,ICE是开源的、免费的,并且版本还不断升级。在运行性能与网络接口处理方面,我们需要测试其稳定性,鲁棒性,健壮性等,研究它是否符合企业用户的业务需求。

1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值