En esta página

Qt Remote Objects - Dispositivos QIODevices externos

Los dispositivos QIODevices externos

Qt Remote Objects admite varios canales de comunicación de forma predeterminada, como el par QTcpServer y QTcpSocket. Dado el « QUrl » deseado para TCP, o el nombre deseado (para el par QLocalServer y QLocalSocket ), el código necesario para escuchar y conectarse es estándar y lo gestiona internamente Qt. « Qt Remote Objects » también admite otros tipos de « QIODevice », y las clases « QRemoteObjectNode » proporcionan métodos adicionales para casos en los que se necesita código personalizado.

A continuación se muestra un ejemplo ficticio con TCP/IP. Un ejemplo más realista utilizaría una conexión SSL, lo que requeriría la configuración 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());
});

El código del lado de la réplica debe conectarse manualmente al 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

Es posible crear cada lado de la « QIODevice » y llamar a QRemoteObjectNode::addClientSideConnection(QIODevice *ioDevice) y QRemoteObjectHostBase::addHostSideConnection(QIODevice *ioDevice), tal y como se muestra más arriba. Esto es totalmente compatible, pero requiere que el cliente sepa cómo establecer la conexión o disponga de un método para obtener esa información. Este es precisamente el problema que el registro fue diseñado para resolver.

Qt Remote Objects También permite utilizar «esquemas externos» con el registro, lo que facilita la configuración de la conexión. En el lado de QRemoteObjectHost, el usuario debe configurar hostUrl con el esquema deseado.

// 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.

Por parte de la réplica, el QRemoteObjectNode debe registrar una función de devolución de llamada que se utilizará cuando se detecte el esquema externo. La función de devolución de llamada debe ser de tipo 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.