Assinatura MQTT via WebSockets
Combinando um cliente MQTT com uma conexão WebSocket.
A assinatura MQTT via WebSockets mostra como projetar um “ QIODevice ” personalizado para combinar uma conexão WebSocket com QMqttClient.
Observação: A partir do Qt 6.10, os WebSockets são suportados nativamente pelo ` Qt MQTT`. Este exemplo foi mantido para demonstrar como implementar um transporte personalizado.
Criação de um QIODevice personalizado
O novo dispositivo personalizado, WebSocketIODevice, deve ser uma subclasse de QIODevice:
class WebSocketIODevice : public QIODevice
{
Q_OBJECT
public:
WebSocketIODevice(QObject *parent = nullptr);
bool isSequential() const override;
qint64 bytesAvailable() const override;
bool open(OpenMode mode) override;
void close() override;
qint64 readData(char *data, qint64 maxlen) override;
qint64 writeData(const char *data, qint64 len) override;
void setUrl(const QUrl &url);
void setProtocol(const QByteArray &data);
Q_SIGNALS:
void socketConnected();
public slots:
void handleBinaryMessage(const QByteArray &msg);
void onSocketConnected();
private:
QByteArray m_protocol;
QByteArray m_buffer;
QWebSocket m_socket;
QUrl m_url;
};Projetando uma classe para gerenciar a conexão e a assinatura
WebSocketIODevice será um membro privado da classe ` ClientSubscription `, juntamente com ` QMqttClient ` e ` QMqttSubscription`:
private:
QMqttClient m_client;
QMqttSubscription *m_subscription;
QUrl m_url;
QString m_topic;
WebSocketIODevice m_device;
int m_version;Assinatura e recebimento de mensagens
A lógica principal está implementada no método ` connectAndSubscribe() ` da classe ` ClientSubscription `. É necessário verificar se o WebSocket se conectou com sucesso antes de inicializar uma conexão MQTT por meio dele. Após o estabelecimento da conexão MQTT, o ` QMqttClient ` pode se inscrever no tópico. Se a inscrição for bem-sucedida, o ` QMqttSubscription ` pode ser usado para receber mensagens do tópico inscrito, que serão tratadas pelo método ` handleMessage() ` da classe ` ClientSubscription `.
void ClientSubscription::connectAndSubscribe()
{
qCDebug(lcWebSocketMqtt) << "Conectando-se ao broker em " << m_url;
m_device.setUrl(m_url);
m_device.setProtocol(m_version== 3 ? "mqttv3.1": "mqtt");
connect(&m_device, &WebSocketIODevice::socketConnected, this, [this]() {
qCDebug(lcWebSocketMqtt) << "WebSocket conectado, inicializando conexão MQTT.";
m_client.setProtocolVersion(m_version== 3 ? QMqttClient::MQTT_3_1 : QMqttClient::MQTT_3_1_1);
m_client.setTransport(&m_device, QMqttClient::IODevice);
connect(&m_client, &QMqttClient::connected, this, [this]() {
qCDebug(lcWebSocketMqtt) << "Conexão MQTT estabelecida";
m_subscription = m_client.subscribe(m_topic);
if (!m_subscription) {
qDebug() << "Failed to subscribe to " << m_topic;
emit errorOccured();
}
connect(m_subscription, &QMqttSubscription::stateChanged,
[](QMqttSubscription::SubscriptionState s) {
qCDebug(lcWebSocketMqtt) << "Estado da assinatura alterado:" << s;
});
connect(m_subscription, &QMqttSubscription::messageReceived,
[this](QMqttMessage msg) {
handleMessage(msg.payload());
});
});
m_client.connectToHost();
});
if (!m_device.open(QIODevice::ReadWrite))
qDebug() << "Could not open socket device";
}Arquivos:
© 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.