2

我想在Qt Remote Objects上做一个简单的通信示例。我想让通信点对点,因此我试图在一个应用程序中合并同一远程对象功能的源和副本(REPC_MERGED用于生成源和副本基类的工具)。

#include <QtCore/QCoreApplication>

#include "MyPeerHost.h"
#include "Client.h"

#include <QDebug>

static QString peer_node_name(int number)
{
    QString ret = QString("peer_%1").arg(number);

    return ret;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    MyPeerHost peerHost; // just inherits auto-generated MyPeerSimpleSource

    QUrl thisAddress = "local:" + peer_node_name(0);

    QRemoteObjectHost sourceNode(thisAddress);

    if(sourceNode.enableRemoting(&peerHost))
    {
        qInfo() << "Source remoting enabled successfully" << thisAddress;

        QUrl remoteAddress = "local:" + peer_node_name(1);

        QSharedPointer<MyPeerReplica> replica;

        QRemoteObjectNode replicaNode;

        if(replicaNode.connectToNode(remoteAddress))
        {
            qInfo() << "Replica connected to the address" << remoteAddress << "successfully";

            replica.reset(replicaNode.acquire<MyPeerReplica>());

            QString sourceClassName = peerHost.staticMetaObject.className();

            qDebug() << "Replica wait for Source" << sourceClassName << "...";

            if(replica->waitForSource(1000))
            {
                qInfo() << "Replica object completely initialized";

                Client client;
                client.setReplicaObject(replica);

                client.sendMessage("AAA");
            }
            else
            {
                qCritical() << "Replica wait for Source" << sourceClassName << "FAILED" << replicaNode.lastError();
            }
        }
        else
        {
            qCritical() << "Replica connect to the address" << remoteAddress << "FAILED" << replicaNode.lastError();
        }
    }
    else
    {
        qCritical() << "Source remoting enable FAILED" << sourceNode.lastError();
    }

    return a.exec();
}

应用输出:

Source remoting enabled successfully QUrl("local:peer_0")
Replica connected to the address QUrl("local:peer_1") successfully
Replica wait for Source "MyPeerHost" ...
Replica wait for Source "MyPeerHost" FAILED QRemoteObjectNode::NoError

如您所见,replicaNode成功连接到不存在的节点QUrl("local:peer_1")
我做错了什么?

4

1 回答 1

0

您没有有效的 Qt 代码。

Qt 依赖于事件循环来处理异步行为,该行为由a.exec()main() 例程的末尾开始。反过来,Qt 远程对象依赖于事件循环进行所有通信。

在您的代码中,您在堆栈上创建对象,但在开始事件循环之前超出范围的代码块中。因此,它们将在事件循环开始之前被破坏。

我建议从一些示例开始,确保它们有效,然后从那里扩展您想要做的事情。

于 2021-11-14T11:30:51.540 回答