1、ICE是什么?

ICE是ZEROC的开源通信协议产品,它的全称是:The Internet Communications Engine,翻译为中文是互联网通信引擎,是一个面向对象的中间件,它封装并实现了底层的通讯逻辑,使我们能够方便的构建分布式应用程序。相对于只面向WINDOWS系统微软的.NET(以及原来的DCOM)、复杂的CORBA及性能较差的WEB SERVICE等分布式方案,ICE很好的解决了这些中间件的不足:它支持不同的系统,如WINDOWS、LINUX等,支持在多种开发语言上使用,如C++、C、JAVA、RUBY、PYTHON、VB等。服务端可以是上面提到的任何一种语言实现的,客户端也可以根据自己的实际情况选择不同的语言实现,如服务端采用C语言实现,而客户端采用JAVA语言实现等。

2: ICE的安装和示例

2.1 ICE安装

   ICE官网:https://zeroc.com,点击download后选择合适的平台/开发环境即可,Ubuntu18.04的安装如下图。

notes: 注意ICE3.7.2与3.6.x版本差异较大,头文件不互相兼容,选用时需注意客户端/服务端ICE版本的一致性,避免代码无法编译通过。

2.2: hello world代码示例

官网的helloworld程序,详见官网目录https://doc.zeroc.com/ice/3.7/hello-world-application

首先创建一个slice文件Printer.ice,并将程序需要远程调用的接口写入其中。对于hello world程序,slice文件可按如下来写:

module Demo
{
interface Printer
{
void printString(string s);
}
}

下面我们以C++(c++11)为例,分别实现服务端和客户端。首先,我们使用slice2cpp将ice文件转换成C++可使用的.h和.cpp文件。其中.h文件中包含了我们需要远程调用的接口定义以及ICE封装,最主要的有Printer和PrinterPrx类,分别是服务端需要实现的具体对象和客户端使用的代理,其中PrinterPrx代理类中还提供了printStringAsync异步调用方法。

slice2cpp Printer.ice                                

服务端需要实现Printer类的接口,并创建本地创建,之后添加到ice适配器上,以便客户端远程调用。具体实现代码如下:

#include <Ice/Ice.h>
#include <Printer.h> using namespace std;
using namespace Demo; class PrinterI : public Printer
{
public:
virtual void printString(string s, const Ice::Current&) override;
}; void
PrinterI::printString(string s, const Ice::Current&)
{
cout << s << endl;
} int
main(int argc, char* argv[])
{
try
{
Ice::CommunicatorHolder ich(argc, argv);
auto adapter = ich->createObjectAdapterWithEndpoints("SimplePrinterAdapter", "default -h localhost -p 10000");
auto servant = make_shared<PrinterI>();
adapter->add(servant, Ice::stringToIdentity("SimplePrinter"));
adapter->activate();
ich->waitForShutdown();
}
catch(const std::exception& e)
{
cerr << e.what() << endl;
return ;
}
return ;
}

客户端需要创建远程对象的代理,并通过代理进行远程调用,代码如下:

#include <Ice/Ice.h>
#include <Printer.h>
#include <stdexcept> using namespace std;
using namespace Demo; int
main(int argc, char* argv[])
{
try
{
Ice::CommunicatorHolder ich(argc, argv);
auto base = ich->stringToProxy("SimplePrinter:default -p 10000");
auto printer = Ice::checkedCast<PrinterPrx>(base);
if(!printer)
{
throw std::runtime_error("Invalid proxy");
} printer->printString("Hello World!");
}
catch(const std::exception& e)
{
cerr << e.what() << endl;
return ;
}
return ;
}

上面的demo演示了ice远程调用的基本工作方式,ICE接口的详细解释既可通过ICE官网查看,也可在安装ICE后查看相应的头文件注释。然而实际工程中我们需要对ice进行配置,处理网络异常,在服务端进行回调,穿透防火墙,进行线程调度等工作。虽然在ICE的chat demo中有介绍这些工作,然而其demo中引入了Glacier2 rooter中session的使用,而github中代码复杂度更高。相反,以上这些工作不通过Glacier2 rooter也能完美的解决,详见如下代码及注释。

完整可运行的Qt工程(可复用的ICE通信模板)可参考https://github.com/leaf-yyl/ice_template

ICE 文件: 定义了一个服务端需要提供的服务 以及一个客户端需要的回调

module Demo
{
interface ServerService
{
void requireService(string ident, string s);
} interface ClientCallback
{
void callback(string s);
}
}

server端代码 : 服务器端worker对象提供具体的服务, ice_manager对象负责ic模块的管理,并接收客户端请求,这些请求会在不同的ICE线程中接收到,然后通过postevent函数最终全部转发到

worker的工作线程并依序处理,如果提供的服务是线程安全的且需要高并发,那么可以去除这一步以获得高性能。相反,如果worker提供的服务不是线程安全的,或者worker中存在线程相关的资源

(例如python解释器等),则必须通过事件循环或者消息队列将ICE线程收到的客户端请求汇总到worker线程统一处理。

#include <QEvent>
#include <QObject>
#include <QCoreApplication> #include <stdexcept> #include <Ice/Ice.h>
#include "Printer.h" using namespace std; class CustomEvent : public QEvent
{
public:
explicit CustomEvent(Type type) :QEvent(type) { } enum PMAlgoEventType {
CustomEvent_RequireService = 0x00000001,
}; string m_params;
Demo::ClientCallbackPrxPtr m_callback;
}; class ServerI : public Demo::ServerService
{
public:
ServerI(){} /* Use event loop implement in QObject by Qt to post client requirements to user thread.
* May be replaced by event loop in pure C++, handler in java and so on.
*/
void setImplement(QObject *implement) {
m_implement = implement;
} void requireService(string ident, string s, const ::Ice::Current& current) override
{
/* we donot generate the client requirement here, but post it to main thread as this function is called in ice server threads.
* When the interface is not thread safe or time-consuming, or has thread associated context like python interpreter, we must post
* it to a constant thread managered by ourself to avoid running exceptions.
* ident : client object identification, used to build bidirectional connection to cross firewall and local network
* s : params used for servcie
*/
CustomEvent *e = new CustomEvent(QEvent::Type(QEvent::User + CustomEvent::CustomEvent_RequireService));
e->m_params = s;
e->m_callback = Ice::uncheckedCast<Demo::ClientCallbackPrx>(current.con->createProxy(Ice::stringToIdentity(ident)));
QCoreApplication::postEvent(m_implement, e);
} private:
QObject *m_implement;
}; class IceManager
{
public:
IceManager() { /* set up global ice configurations, here we just set thread pool to 2 to avoid deadlock on ice callback,
* other settings are configurable as the same.
*/
Ice::PropertiesPtr props0 = Ice::createProperties();
props0->setProperty("Ice.ThreadPool.Server.Size", "");
props0->setProperty("Ice.ThreadPool.Server.SizeMax", "");
props0->setProperty("Ice.ThreadPool.Client.Size", "");
props0->setProperty("Ice.ThreadPool.Client.SizeMax", "");
props0->setProperty("Ice.Trace.ThreadPool", ""); Ice::InitializationData id;
id.properties = props0;
m_ich = Ice::CommunicatorHolder(id);
} bool setImplement(QObject *implement) {
try {
/* create server object and add it to ice adapter to receive client requirements.
* The adapter identification is used for ice pack service, we donot use it now.
* The endpoints is the location url where client can access to require service.
* The servant identification is used to identify servant as we can add multiple servants to one adapter.
*/
shared_ptr<ServerI> servant = make_shared<ServerI>();
servant->setImplement(implement);
auto adapter = m_ich->createObjectAdapterWithEndpoints("ServerAdapter", "default -h localhost -p 10000");
adapter->add(servant, Ice::stringToIdentity("Server"));
adapter->activate();
} catch (const exception &e)
{
cout << "Failed to create ice server object, error-->%s" << e.what() << endl;
return false;
} return true;
} private:
Ice::CommunicatorHolder m_ich;
}; class MainWorker : public QObject
{
public:
MainWorker(QObject *parent = nullptr) : QObject(parent) {} protected: /* Receive client requirements and deliver to associated servcie function */
void customEvent(QEvent *e) {
CustomEvent *event = (CustomEvent *)e; int type = event->type() - QEvent::User;
if (CustomEvent::CustomEvent_RequireService == type) {
renderService(event->m_params, event->m_callback);
} else {
cout << "Unrecognized event type-->" << type << "!" << endl;
}
} private:
/* a simple implement */
void renderService(const string& s, const Demo::ClientCallbackPrxPtr& callback) {
cout << s << endl;
callback->callback("Requirement done!");
}
}; int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv); MainWorker worker(&a); IceManager ice_manager;
ice_manager.setImplement(&worker); return a.exec();
}

client端 头文件代码:客户端基本上与服务端类似, 但是多了一个主动发起请求的IceRequirer类,并在IceRequirer中设置链接参数等创建保活的ICE链接,达到与服务端的双向通信,具体原因

见代码注释。

#ifndef HELPER_H
#define HELPER_H #include <QTimer>
#include <QEvent>
#include <QObject>
#include <QThread>
#include <QCoreApplication> #include <stdexcept> #include <Ice/Ice.h>
#include "Printer.h" using namespace std; /* custom event used for event loop */
class CustomEvent : public QEvent
{
public:
explicit CustomEvent(Type type) :QEvent(type) {} enum PMAlgoEventType {
CustomEvent_RequireCallback = 0x00000001,
}; string m_params;
}; class ClientI : public Demo::ClientCallback
{
public:
ClientI(){} /* Use event loop implement in QObject by Qt to post client requirements to user thread.
* May be replaced by event loop in pure C++, handler in java and so on.
*/
void setImplement(QObject *implement) {
m_server_implement = implement;
} void callback(string s, const ::Ice::Current&) override
{
/* we donot generate the client requirement here, but post it to main thread as this function is called in ice server threads.
* When the interface is not thread safe or time-consuming, or has thread associated context like python interpreter, we must post
* it to a constant thread managered by ourself to avoid running exceptions.
* s : params used for servcie
*/
CustomEvent *e = new CustomEvent(QEvent::Type(QEvent::User + CustomEvent::CustomEvent_RequireCallback));
e->m_params = s;
QCoreApplication::postEvent(m_server_implement, e);
} private:
QObject *m_server_implement;
}; class ServerRequirer : public QObject
{
Q_OBJECT
public:
explicit ServerRequirer(const Ice::CommunicatorHolder &ich, const Ice::ObjectAdapterPtr &adapter, const string& ident) {
m_ic = ich.communicator();
m_adapter = adapter;
m_ident = ident;
} public slots:
void slot_requireServcie(const string& s) {
if (nullptr == m_server_prx.get()) {
/* connection is not established, try to establish connection first */
try {
auto base = m_ic->stringToProxy("Server:default -h localhost -p 10000");
m_server_prx = Ice::checkedCast<Demo::ServerServicePrx>(base);
if(nullptr != m_server_prx.get())
{
/* set up eseential configurations on Ice connection to keep this connection alive */
m_server_prx->ice_getConnection()->setACM(Ice::nullopt, Ice::ACMClose::CloseOff, Ice::ACMHeartbeat::HeartbeatAlways);
m_server_prx->ice_getConnection()->setAdapter(m_adapter);
}
}
catch(const exception& e)
{
cerr << e.what() << endl;
}
} if (nullptr != m_server_prx.get()) {
try {
/* require remote object call via object proxy */
m_server_prx->requireService(m_ident, s);
}
catch(const exception& e)
{
/* connection lost, reset it and re-establish it on next call */
cerr << e.what() << endl;
m_server_prx.reset();
}
}
} private:
string m_ident;
Ice::CommunicatorPtr m_ic;
Ice::ObjectAdapterPtr m_adapter;
Demo::ServerServicePrxPtr m_server_prx;
}; class IceManager : public QThread
{
Q_OBJECT
public:
/* Craete ice global communicator and manager ice requirement.
* Server requirements are posted in seperate thread as they may be time-consuming
* Local object that implements callback is identified through bidirectional connection instead of
* creating a new connection fron server to client, as client may be defensed behind firewall or local network.
*/
IceManager() { /* register qt meta type */
qRegisterMetaType<string>("string"); /* set up global ice configurations, here we just set thread pool to 2 to avoid deadlock on ice callback,
* other settings are configurable as the same.
*/
Ice::PropertiesPtr props0 = Ice::createProperties();
props0->setProperty("Ice.ThreadPool.Server.Size", "");
props0->setProperty("Ice.ThreadPool.Server.SizeMax", "");
props0->setProperty("Ice.ThreadPool.Client.Size", "");
props0->setProperty("Ice.ThreadPool.Client.SizeMax", "");
props0->setProperty("Ice.Trace.ThreadPool", ""); /* create global ice communicator */
Ice::InitializationData id;
id.properties = props0;
m_ich = Ice::CommunicatorHolder(id);
} bool start(QObject *implement) { try {
/* create client object and add it to ice adapter to receive server callbacks.
* The adapter is created without identification as we donot access it by endpoints.
* Instead, we pass it through the connection established with server to build a bidirectional connection.
*/
m_ident = "Client";
shared_ptr<ClientI> servant = make_shared<ClientI>();
servant->setImplement(implement);
m_adapter = m_ich->createObjectAdapter("");
m_adapter->add(servant, Ice::stringToIdentity(m_ident));
m_adapter->activate();
} catch (const exception &e) {
cout << "Failed to create ice object, error-->%s" << e.what() << endl;
return false;
} /* create ice service requirer in seperate thread, as network request may be time-consuming */
m_requirer = new ServerRequirer(m_ich, m_adapter, m_ident);
m_requirer->moveToThread(this);
connect(this, SIGNAL(signal_requireService(string)), m_requirer, SLOT(slot_requireServcie(string))); QThread::start();
return true;
} public slots:
void slot_requireService() {
string s("Hello world!");
emit signal_requireService(s);
} signals:
void signal_requireService(string s); private:
Ice::CommunicatorHolder m_ich;
Ice::ObjectAdapterPtr m_adapter; string m_ident; /* local object identification */
ServerRequirer *m_requirer;
}; class MainWorker : public QObject
{
public:
MainWorker(QObject *parent = nullptr) : QObject(parent) {} protected: /* Receive callbacks from server and deliver to associated callback function */
void customEvent(QEvent *e) {
CustomEvent *event = (CustomEvent *)e; int type = event->type() - QEvent::User;
if (CustomEvent::CustomEvent_RequireCallback == type) {
renderCallback(event->m_params);
} else {
cout << "Unrecognized event type-->" << type << "!" << endl;
}
} private:
/* a simple implement */
void renderCallback(const string& s) {
cout << s << endl;
}
}; #endif // HELPER_H

client main文件代码

#include "helper.h"

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv); /* local worker */
MainWorker worker(&a); /* ice service manager */
IceManager ice_manager;
ice_manager.start(&worker); /* require serve service every 3 seconds */
QTimer timer;
QObject::connect(&timer, SIGNAL(timeout()), &ice_manager, SLOT(slot_requireService()));
timer.start( * ); return a.exec();
}

Ice简介+Qt代码示例的更多相关文章

  1. JUC组件扩展(二)-JAVA并行框架Fork/Join(一):简介和代码示例

    一.背景 虽然目前处理器核心数已经发展到很大数目,但是按任务并发处理并不能完全充分的利用处理器资源,因为一般的应用程序没有那么多的并发处理任务.基于这种现状,考虑把一个任务拆分成多个单元,每个单元分别 ...

  2. 【嵌入式开发】裸机引导操作系统和ARM 内存操作 ( DRAM SRAM 类型 简介 | Logical Bank | 内存地址空间介绍 | 内存芯片连接方式 | 内存初始化 | 汇编代码示例 )

    [嵌入式开发]ARM 内存操作 ( DRAM SRAM 类型 简介 | Logical Bank | 内存地址空间介绍 | 内存芯片连接方式 | 内存初始化 | 汇编代码示例 )     一. 内存 ...

  3. 2018-06-20 中文代码示例视频演示Python入门教程第三章 简介Python

    知乎原链 Python 3.6.5官方入门教程中示例代码汉化后演示 对应在线文档: 3. An Informal Introduction to Python 不知如何合集, 请指教. 中文代码示例P ...

  4. ICE简介及C++程序例子(转)

    一.ICE简介: 1.ICE是什么? ICE是ZEROC的开源通信协议产品,它的全称是:The Internet Communications Engine,翻译为中文是互联网通信引擎,是一个面向对象 ...

  5. 领域驱动开发推荐代码示例 — Microsoft NLayerApp

    简介: Microsoft NLayerApp是由微软西班牙团队出品的基于.NET 4.0的“面向领域N层分布式架构”代码示例,在codeplex上的地址是:http://microsoftnlaye ...

  6. 英特尔实感SDK 代码示例

    原文地址 摘要 本套代码示例针对巴西英特尔实感动手实验室创建,旨在帮助参与人员了解如何使用英特尔® 实感™ 软件开发套件. 12 个示例使用 C# SDK 包装程序,提供了简单的基于控制台的应用,支持 ...

  7. JAVA NIO工作原理及代码示例

    简介:本文主要介绍了JAVA NIO中的Buffer, Channel, Selector的工作原理以及使用它们的若干注意事项,最后是利用它们实现服务器和客户端通信的代码实例. 欢迎探讨,如有错误敬请 ...

  8. 全国天气预报信息数据 API 功能简介与代码调用实战视频

    此文章对开放数据接口 API 之「全国天气预报信息数据 API」进行了功能介绍.使用场景介绍以及调用方法的说明,供用户在使用数据接口时参考之用,并对实战开发进行了视频演示. 1. 产品功能 接口开放了 ...

  9. 2018-06-20 中文代码示例视频演示Python入门教程第四章 控制流

    知乎原链 续前作: 中文代码示例视频演示Python入门教程第三章 简介Python 对应在线文档: 4. More Control Flow Tools 录制中出了不少岔子. 另外, 输入法确实是一 ...

随机推荐

  1. hdu 5089 使做对k-1题最大概率的选题方案

    http://acm.hdu.edu.cn/showproblem.php?pid=5089 给出N道难度递增的题目,难度用可能做出的百分比表示,选出K道题目使得做出K-1道题目的概率最大. 选k题的 ...

  2. Linux-目录与文件

    1. pwd - 打印当前工作目录 [root@VM_0_171_centos ~]# pwd /root 2. cd - Change the shell working directory. [r ...

  3. C#调用haskell遭遇Attempted to read or write protected memory

    1. Haskell的代码如下: 上面的代码中readMarkdown与writeHtmlString是pandoc中的函数,newString的作用是将String转换为IO CString. 2. ...

  4. 混合式应用开发之AngularJS ng-repeat数组有重复值的解决方法

    使用AngularJS ng-repeat遍历数组时,遇到数组里又重复值时会报错.例如数组[1,2,3,3] 官网给了一个解决的方案 <div ng-repeat="value in ...

  5. python做数据分析pandas库介绍之DataFrame基本操作

    怎样删除list中空字符? 最简单的方法:new_list = [ x for x in li if x != '' ] 这一部分主要学习pandas中基于前面两种数据结构的基本操作. 设有DataF ...

  6. 浏览器环境下JavaScript脚本加载与执行探析之代码执行顺序

    本文主要基于向HTML页面引入JavaScript的几种方式,分析HTML中JavaScript脚本的执行顺序问题 1. 关于JavaScript脚本执行的阻塞性 JavaScript在浏览器中被解析 ...

  7. 常用下载方式的区别-BT下载、磁力链接、电驴

    出处:https://www.jianshu.com/p/72b7a64e5be1 打开 115 离线下载的窗口,看到支持这么多种链接,你都清楚他们是什么原理嘛?接下来我们一个一个说. 一.HTTP( ...

  8. Shell - 简明Shell入门01 - 第一个脚本(HelloShell)

    示例脚本及注释 #!/bin/bash echo "hello shell!" # 打印字符串"hello shell!" echo "Date: & ...

  9. Docker - 基础讲义

    Docker Docker - 官网 Docker - Hub GitHub - Docker dockerinfo Docker中文社区 Docker入门教程 Docker从入门到实践 虚拟化技术 ...

  10. Angular使用总结 --- 搜索场景中使用rxjs的操作符

    在有input输入框的搜索/过滤业务中,总会考虑如何减少发起请求频率,尽量使每次的请求都是有效的.节流和防抖是比较常见的做法,这类函数的实现方式也不难,不过终归还是需要自己封装.rxjs提供了各种操作 ...