Nesta página

Qt Remote Objects - Dispositivos QIODevices externos

QIODevices externos

Qt Remote Objects oferecem suporte a vários canais de comunicação prontos para uso, como o par QTcpServer e QTcpSocket. Dado o endereço de origem ( QUrl ) desejado para TCP, ou o nome desejado (para o par QLocalServer e QLocalSocket ), o código necessário para escutar e se conectar é padrão e tratado internamente pelo Qt. O ` Qt Remote Objects ` também suporta outros tipos de endereços de destino ( QIODevice ), e as classes ` QRemoteObjectNode ` fornecem métodos adicionais para lidar com casos em que é necessário código personalizado.

Um exemplo simplificado com TCP/IP é mostrado abaixo. Um exemplo mais realista utilizaria uma conexão SSL, o que exigiria a configuração de certificados, etc.

// Create the server and listen outside of QtRO
QTcpServer tcpServer;
tcpServer.listen(QHostAddress(QStringLiteral("127.0.0.1")), 65213);

// Create the host node.  We don't need a hostUrl unless we want to take
// advantage of external schemas (see next example).
QRemoteObjectHost srcNode;

// Make sure any connections are handed to QtRO
QObject::connect(&tcpServer, &QTcpServer::newConnection, &srcNode,
                 [&srcNode, &tcpServer]() {
    srcNode.addHostSideConnection(tcpServer.nextPendingConnection());
});

O código do lado da réplica precisa se conectar manualmente ao host

QRemoteObjectNode repNode;
QTcpSocket *socket = new QTcpSocket(&repNode);
QObject::connect(socket, &QTcpSocket::connected, &repNode,
        [socket, &repNode]() {
    repNode.addClientSideConnection(socket);
});
socket->connectToHost(QHostAddress(QStringLiteral("127.0.0.1")), 65213);

Esquemas externos

É possível criar cada lado do QIODevice e chamar QRemoteObjectNode::addClientSideConnection(QIODevice *ioDevice) e QRemoteObjectHostBase::addHostSideConnection(QIODevice *ioDevice), conforme mostrado acima. Isso é totalmente suportado, mas exige que o cliente saiba como estabelecer a conexão ou tenha uma maneira de descobrir essa informação. Esse é exatamente o problema que o registro foi projetado para resolver.

Qt Remote Objects Também permite que “Esquemas Externos” sejam usados com o registro, o que ajuda na configuração da conexão. No lado do QRemoteObjectHost, o usuário deve definir o hostUrl com o esquema desejado.

// Use standard tcp url for the registry
const QUrl registryUrl = QUrl(QStringLiteral("tcp://127.0.0.1:65212"));
// Use "exttcp" for the "external" interface
const QUrl extUrl = QUrl(QStringLiteral("exttcp://127.0.0.1:65213"));

// Create the server and listen outside of QtRO
QTcpServer tcpServer;
tcpServer.listen(QHostAddress(extUrl.host()), extUrl.port());

// We need a registry for everyone to connect to
QRemoteObjectRegistryHost registry(registryUrl);

// Finally, we create our host node and register "exttcp" as our schema.
// We need the AllowExternalRegistration parameter to prevent the node from
// setting a hostUrlInvalid error.
QRemoteObjectHost srcNode(extUrl, registryUrl, QRemoteObjectHost::AllowExternalRegistration);
// From now on, when we call enableRemoting() from this node, the registry
// will be updated to show the Source object at extUrl.

No lado da réplica, o QRemoteObjectNode precisa registrar um callback a ser usado quando o esquema externo for detectado. O callback deve ser um RemoteObjectSchemaHandler.

// Use standard tcp url for the registry
const QUrl registryUrl = QUrl(QStringLiteral("tcp://127.0.0.1:65212"));

// This time create the node connected to the registry
QRemoteObjectNode repNode(registryUrl);

// Create the RemoteObjectSchemaHandler callback
QRemoteObjectNode::RemoteObjectSchemaHandler setupTcp = [&repNode](QUrl url) {
    QTcpSocket *socket = new QTcpSocket(&repNode);
    connect(socket, &QTcpSocket::connected,
            [socket, &repNode]() {
        repNode.addClientSideConnection(socket);
    });
    connect(socket, &QSslSocket::errorOccurred,
            [socket](QAbstractSocket::SocketError error) {
        delete socket;
    });
    socket->connectToHost(url.host(), url.port());
};

// Once we call registerExternalSchema, the above method will be called
// whenever the registry sees an object we are interested in on "exttcp"
repNode.registerExternalSchema(QStringLiteral("exttcp"), setupTcp);

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.