Qt Remote Objects (QtRO) 笔记

简介

Qt Remote Objects (QtRO) 是 Qt 的一个进程间通信模块。

术语

Source 是指提供服务或提供功能供其他程序使用的对象,是 RPC 中的被调用端。

Replica 是指 Source 对象的代理对象,用于 RPC 中的调用端,对 Replica 的调用请求将被转发给 Source 对象。

示例1:Direct Connection using a Static Source

创建接口定义文件

创建接口定义文件 simpleswitch.rep :

复制代码
class SimpleSwitch
{
  PROP(bool currState=false);
  SLOT(server_slot(bool clientState));
};

修改 .pro 文件

复制代码
// 引入 QtRO 模块
QT += remoteobjects
// 引入接口定义文件
REPC_SOURCE = simpleswitch.rep

Qt 将使用 repc 工具编译该接口定义文件生成 C++ 代码。

生成的文件:

  • rep_simpleswitch_source.h
  • rep_simpleswitch_replica.h

rep_simpleswitch_source.h 用于 Source 端,需要继承其中的接口类,实现其中的虚函数。

rep_simpleswitch_replica.h 用于 Replica 端,是 Source 对象的代理对象。

Source 端

实现 rep_simpleswitch_source.h 中接口类的虚函数,作为服务对象。

创建服务对象,并设置为可远程访问:

c++ 复制代码
SimpleSwitch srcSwitch; // create simple switch

QRemoteObjectHost srcNode(QUrl(QStringLiteral("local:replica"))); // create host node without Registry
srcNode.enableRemoting(&srcSwitch); // enable remoting/Sharing

Replica 端

连接到服务端:

c++ 复制代码
QSharedPointer<SimpleSwitchReplica> ptr;

QRemoteObjectNode repNode; // create remote object node
repNode.connectToNode(QUrl(QStringLiteral("local:replica"))); // connect with remote host node

ptr.reset(repNode.acquire<SimpleSwitchReplica>()); // acquire replica of source from host node

获取到 SimpleSwitchReplica 对象指针之后,就可以像使用普通 Qt 对象那样使用该对象,该对象拥有和服务对象相同的接口函数(信号函数、槽函数等)。

客户端也可以不使用 rep_simpleswitch_replica.h ,而是使用 QRemoteObjectDynamicReplica 类来动态地与服务对象交互。

示例2:Connections to Remote Nodes using a Registry

第一个示例是采用直接连接的方式,即代理对象直接连接到服务对象。

另一种方式是使用注册中心,此时服务对象将自己注册到服务中心,客户端连接到注册中心,然后获取指定服务对象的代理对象。

服务端:

c++ 复制代码
// 注册中心,可以在一个单独的进程中
QRemoteObjectRegistryHost regNode(QUrl(QStringLiteral("local:registry"))); // create node that hosts registy

// 服务对象
SimpleSwitch srcSwitch; // create simple switch

// 在注册中心上注册服务对象
QRemoteObjectHost srcNode(QUrl(QStringLiteral("local:replica")), QUrl(QStringLiteral("local:registry"))); // create node that will host source and connect to registry
srcNode.enableRemoting(&srcSwitch); // enable remoting of source object

客户端:

c++ 复制代码
QSharedPointer<SimpleSwitchReplica> ptr;

QRemoteObjectNode repNode(QUrl(QStringLiteral("local:registry")));

ptr.reset(repNode.acquire<SimpleSwitchReplica>()); // acquire replica of source from host node
相关推荐
C++ 老炮儿的技术栈31 分钟前
Linux 文件系统目录架构全解析
linux·服务器·c语言·开发语言·c++
样例过了就是过了41 分钟前
LeetCode热题100 分割回文串
数据结构·c++·算法·leetcode·深度优先·dfs
阿猿收手吧!1 小时前
【C++】高并发内存池架构与设计解析
开发语言·c++·架构
唠玖馆1 小时前
c++ 类和对象(全)
java·开发语言·c++
Morwit2 小时前
【力扣hot100】 85. 最大矩形
c++·算法·leetcode·职场和发展
m0_528174452 小时前
C++中的代理模式变体
开发语言·c++·算法
mjhcsp2 小时前
C++ 折半搜索(Meet in the Middle):突破指数级复杂度的分治策略
开发语言·c++
2401_883035462 小时前
C++代码风格检查工具
开发语言·c++·算法
爱思考的小伙2 小时前
Qt-02:信号与槽
开发语言·qt
Vae_Mars2 小时前
华睿MVP:C#脚本的应用一
笔记·c#