在源端不需要做任何更改,因为动态副本只会影响请求者节点获取副本的方式。因此,我们使用上一章节中所示的源代码。
因为replica 是动态获取的,所以不需要rep文件。
此步骤的代码与示例1 directconnectclient 中的代码相同
QRemoteObjectNode repNode; // create remote object node
repNode.connectToNode(QUrl(QStringLiteral("local:switch"))); // connect with remote host node
#include <QCoreApplication>
#include "dynamicclient.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSharedPointer<QRemoteObjectDynamicReplica> ptr; // shared pointer to hold replica
QRemoteObjectNode repNode;
repNode.connectToNode(QUrl(QStringLiteral("local:switch")));
ptr.reset(repNode.acquireDynamic("SimpleSwitch")); // acquire replica of source from host node
DynamicClient rswitch(ptr); // create client switch object and pass replica reference to it
}
dynamicclient.h
#ifndef _DYNAMICCLIENT_H
#define _DYNAMICCLIENT_H
#include <QObject>
#include <QSharedPointer>
#include <QRemoteObjectNode>
#include <qremoteobjectdynamicreplica.h>
class DynamicClient : public QObject
{
Q_OBJECT
public:
DynamicClient(QSharedPointer<QRemoteObjectDynamicReplica> ptr);
~DynamicClient();
Q_SIGNALS:
void echoSwitchState(bool switchState);// this signal is connected with server_slot(..) slot of source object and echoes back switch state received from source
public Q_SLOTS:
void recSwitchState_slot(); // Slot to receive source state
void initConnection_slot(); //Slot to connect signals/slot on replica initialization
private:
bool clientSwitchState; // holds received server switch state
QSharedPointer<QRemoteObjectDynamicReplica> reptr;// holds reference to replica
};
#endif
dynamicclient.cpp
#include "dynamicclient.h"
// constructor
DynamicClient::DynamicClient(QSharedPointer<QRemoteObjectDynamicReplica> ptr) :
QObject(nullptr), reptr(ptr)
{
//connect signal for replica valid changed with signal slot initialization
QObject::connect(reptr.data(), SIGNAL(initialized()), this, SLOT(initConnection_slot()));
}
//destructor
DynamicClient::~DynamicClient()
{
}
// Function to initialize connections between slots and signals
void DynamicClient::initConnection_slot()
{
// connect source replica signal currStateChanged() with client's recSwitchState() slot to receive source's current state
QObject::connect(reptr.data(), SIGNAL(currStateChanged()), this, SLOT(recSwitchState_slot()));
// connect client's echoSwitchState(..) signal with replica's server_slot(..) to echo back received state
QObject::connect(this, SIGNAL(echoSwitchState(bool)),reptr.data(), SLOT(server_slot(bool)));
}
void DynamicClient::recSwitchState_slot()
{
clientSwitchState = reptr->property("currState").toBool(); // use replica property to get currState from source
qDebug() << "Received source state " << clientSwitchState;
Q_EMIT echoSwitchState(clientSwitchState); // Emit signal to echo received state back to server
}
即我们需要
QObject::connect(reptr.data(), SIGNAL(initialized()), this, SLOT(initConnection_slot()));
收到initialized信号后,才初始化我们的副本端代码(需要用到source信息)
有了静态和动态两种方式后我们该如何选择呢?在这里我根据自己的实践经验给出一个比较:
优:
缺:
动态方式的优劣:
优:
缺: