简单的 MQTT 客户端
创建简约的遥测应用程序。
Simple MQTT Client演示了如何创建一个简约的客户端应用程序。
要使用该应用程序,首先要指定一个代理(如test.mosquitto.org或broker.hivemq.com)和端口号 1883,然后连接到该代理。然后,您可以订阅一个主题并发送信息,您也会收到该信息。
注意: 端口号 1883 未加密,因此仅适用于开发和测试目的。在生产中,请始终使用加密连接。
创建客户端
首先,我们使用QMqttClient 类创建一个 MQTT 客户端。该类提供了用于设置唯一客户端 ID 以及要连接的代理主机名和端口的属性:
m_client = new QMqttClient(this); m_client->setHostname(ui->lineEditHost->text()); m_client->setPort(static_cast<quint16>(ui->spinBoxPort->value()));
我们不设置客户端 ID,因此它会自动为我们生成。
接下来,我们连接到QMqttClient::messageReceived() 以接收发送到代理的所有消息:
connect(m_client, &QMqttClient::messageReceived, this, [this](const QByteArray &message, const QMqttTopicName &topic) { const QString content = QDateTime::currentDateTime().toString() + " Received Topic: "_L1 + topic.name() + " Message: "_L1 + message + u'\n'; ui->editLog->insertPlainText(content); });
当用户在客户端订阅主题时,我们会在指定的主题上调用QMqttClient::subscribe() :
void MainWindow::on_buttonSubscribe_clicked() { auto subscription = m_client->subscribe(ui->lineEditTopic->text()); if (!subscription) { QMessageBox::critical(this, u"Error"_s, u"Could not subscribe. Is there a valid connection?"_s); return; }
在本例中,我们订阅了所有主题。有关如何接收特定主题消息的更多信息,请参阅MQTT 订阅示例。
有关如何在Qt Quick 应用程序中使用QMqttClient 类的示例,请参阅Qt Quick Subscription。
文件:
© 2025 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.