Ice-Internet Communications Engine,是一种面向对象、跨平台、多语言的通信中间件。支持C++、Java、C#、VB、Python等,客户和服务器可以用不同的语言,可以运行在不同的操作系统和机器架构上,支持TCP/UDP。
Ice应用组成:
Ice对象——Ice对象是在本地或远地的地址空间中、能响应客户请求的实体。先由Slice定义,然后编译成特定语言版本;每个Ice对象有多个接口,支持特定操作,客户通过调用它的接口来发出请求;每个对象有唯一的对象标识。
Servants——服务器端编写的类实例,体现Ice对象行为。
代理(Proxies)——代理是Ice对象在客户端的代表,客户调用代理上的操作来获得服务端上Ice对象提供的服务。
通信器(Ice::Communicator)——通信时,服务器和客户建立一个通信器,为通信进程分配和管理资源,是双方通信的专用线路。
对象适配器(object adapter)——专用于服务器端的Ice API,把Ice run time与服务端编写的Servant类连接在一起。每个适配器绑定一个端口。
Ice应用的结构如下:
Slice
Slice (Specification Language for Ice, Ice规范语言),用于对象接口定义与实现相分离的基础性抽象机制,可以把定义好的Ice对象映射成特定语言。
Slice开发过程见下图:
相同开发环境
不同开发环境:
Ice应用开发过程:
1. 定义Ice对象(Printer.ice)
module Demo{
interface Printer{
void printString(string s);
};
}
2. 编译成C++
slice2cpp Printer.ice
获得Printer.h/Printer.cpp
3.服务端使用C++实现Ice对象(Servant类)
#include <Ice/Ice.h>
#include <Printer.h>
using namespace std;
using namespace Demo;
class PrinterI:public Printer{
public:
virtual void printString(const string& s,const Ice::Current&);
};
void PrinterI::printString(const string& s, const Ice::Currrent&){
cout<<s<<endl;
}
Ice::CommunicatorPtr ic;
//建立通信器
ic=Ice::initialize(argc, argv);
//建立对象适配器,绑定端口
Ice::ObjectAdapterPtr adapter=ic->createObjectAdapterWithEndpoints(
"simplePrinterAdapter","default -p 10000");
Ice::ObjectPtr object = new PrinterI;
//加入Ice对象实例,指定标识符
adapter->add(object,ic->stringToIdentity("SimplePrinter"));
//启动适配器
adapter->activate();
//挂起该进程
ic->waitForShutdown();
#include <Ice/Ice.h>
#include <Printer.h>
using namespace std;
using namespace Demo;
Ice::CommunicatorPtr ic;
//建立通信器
ic = Ice::initialize(argc, argv);
//获得Ice对象代理,SimplePrinter-对象标识符,default -p 10000-协议与端口
Ice::ObjectPrx base = ic->stringToProxy("SimplePrinter:default -p 10000");
//向下转换
PrinterPrx printer = PrinterPrx::checkedCast(base);
if (!printer) throw "Invalid proxy";
//调用操作
printer->printString("Hello World!");
6.编译
//服务端
c++ -I. -I$ICE_HOME/include -c Printer.cpp Server.cpp
c++ -o server Printer.o Server.o -L$ICE_HOME/lib -lIce -lIceUtil
//客户端
c++ -I. -I$ICE_HOME/include -c Printer.cpp Client.cpp
c++ -o client Printer.o Client.o -L$ICE_HOME/lib -lIce -lIceUtil
7.运行
服务器端./server,客户端./client