シンプルな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 Subscriptions の例を参照してください。
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.