간단한 MQTT 클라이언트
최소한의 원격 분석 애플리케이션 만들기.
Simple MQTT 클라이언트는 최소한의 클라이언트 애플리케이션을 만드는 방법을 보여줍니다.
애플리케이션을 사용하려면 먼저 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 구독을 참조하세요.
파일:
© 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.