MQTT 구독
MQTT 브로커와 통신하는 애플리케이션 만들기.
MQTT 구독 은 MQTT 브로커와 통신하는 애플리케이션을 만드는 방법을 보여줍니다. 각 구독에 대해 새 대화 상자가 열리며, 여기서 구독한 주제에 대한 메시지를 볼 수 있습니다.
클라이언트 만들기
QMqttClient 클래스를 사용하여 MQTT 클라이언트를 만들고 연결에 사용할 브로커 호스트 이름과 포트를 설정합니다:
m_client = new QMqttClient(this); m_client->setHostname(ui->lineEditHost->text()); m_client->setPort(static_cast<quint16>(ui->spinBoxPort->value()));
토픽 구독하기
사용자가 클라이언트에서 토픽을 구독하면 새 구독 개체가 만들어집니다:
void MainWindow::on_buttonSubscribe_clicked() { auto subscription = m_client->subscribe(ui->lineEditTopic->text(), static_cast<quint8>(ui->spinQoS->text().toUInt())); if (!subscription) { QMessageBox::critical(this, u"Error"_s, u"Could not subscribe. Is there a valid connection?"_s); return; } auto subWindow = new SubscriptionWindow(subscription); subWindow->setWindowTitle(subscription->topic().filter()); subWindow->show(); }
QMqttSubscription 클래스를 사용하여 구독의 토픽, 상태 및 QoS 수준을 저장합니다:
SubscriptionWindow::SubscriptionWindow(QMqttSubscription *sub, QWidget *parent) : QWidget(parent), ui(new Ui::SubscriptionWindow), m_sub(sub) { ui->setupUi(this); ui->labelSub->setText(m_sub->topic().filter()); ui->labelQoS->setText(QString::number(m_sub->qos())); updateStatus(m_sub->state()); connect(m_sub, &QMqttSubscription::messageReceived, this, &SubscriptionWindow::updateMessage); connect(m_sub, &QMqttSubscription::stateChanged, this, &SubscriptionWindow::updateStatus); connect(m_sub, &QMqttSubscription::qosChanged, [this](quint8 qos) { ui->labelQoS->setText(QString::number(qos)); }); connect(ui->pushButton, &QAbstractButton::clicked, m_sub, &QMqttSubscription::unsubscribe); }
QoS 수준은 메시지와 구독에 대해 별도로 설정할 수 있습니다. 가입에 대해 설정된 QoS 수준에 따라 최소 QoS 수준이 결정됩니다. 메시지가 더 높은 QoS 수준으로 전송되면 브로커는 해당 메시지의 QoS를 더 높은 수준으로 높입니다. 예를 들어 클라이언트 A가 QoS 1로 토픽을 구독했는데 클라이언트 B가 해당 토픽에 대해 QoS 0으로 메시지를 게시하면 브로커는 자동으로 메시지의 QoS를 1로 높이고, 클라이언트 B가 QoS 2로 토픽에 대해 메시지를 게시하면 브로커는 QoS 2로 메시지를 전송합니다.
메시지 받기
클라이언트가 메시지를 수신하면 QMqttMessage 클래스가 실제 메시지 페이로드를 저장하는 데 사용됩니다:
void SubscriptionWindow::updateMessage(const QMqttMessage &msg) { ui->listWidget->addItem(msg.payload()); }
파일입니다:
© 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.