Qt - QMQTT订阅者和发布者

简介

使用Qt官方提供的QMQTT源代码编译为QMQTT模块,来编写简单的订阅者和发布者。

 

订阅者

 1 #ifndef SUBSCRIBER_H
 2 #define SUBSCRIBER_H
 3 
 4 #include <QObject>
 5 
 6 #include <QDebug>
 7 #include <qmqtt.h>
 8 #include <QTimer>
 9 
10 
11 //订阅
12 class Subscriber : public QMQTT::Client {
13     Q_OBJECT
14   public:
15     explicit Subscriber(const QHostAddress& host,
16                         const quint16 port,
17                         QObject* parent = NULL)
18         : QMQTT::Client(host, port, parent)
19         , _qout(stdout) {
20         connect(this, &Subscriber::connected, this, &Subscriber::onConnected);
21         connect(this, &Subscriber::subscribed, this, &Subscriber::onSubscribed);
22         connect(this, &Subscriber::received, this, &Subscriber::onReceived);
23     }
24     virtual ~Subscriber() {}
25 
26     QTextStream _qout;
27 
28   public slots:
29     void onConnected() {
30         qDebug() << "connected" << endl;
31         subscribe("qmqtt/exampletopic", 0);
32     }
33 
34     void onSubscribed(const QString& topic) {
35         qDebug() << "subscribed " << topic << endl;
36     }
37 
38     void onReceived(const QMQTT::Message& message) {
39         qDebug() << "publish received: \""
40                  << QString::fromUtf8(message.payload())
41                  << "\"" << endl;
42     }
43 };
44 
45 
46 #endif // SUBSCRIBER_H

 

发布者

 1 #ifndef PUBLISHER_H
 2 #define PUBLISHER_H
 3 
 4 #include <QObject>
 5 
 6 #include <QDebug>
 7 #include <qmqtt.h>
 8 #include <QTimer>
 9 
10 //发布
11 class Publisher : public QMQTT::Client {
12     Q_OBJECT
13   public:
14     explicit Publisher(const QHostAddress& host,
15                        const quint16 port,
16                        QObject* parent = NULL)
17         : QMQTT::Client(host, port, parent), _number(0) {
18 
19         connect(this, &Publisher::connected, this, &Publisher::onConnected);
20         connect(&_timer, &QTimer::timeout, this, &Publisher::onTimeout);
21         connect(this, &Publisher::disconnected, this, &Publisher::onDisconnected);
22     }
23     virtual ~Publisher() {}
24 
25     QTimer _timer;
26     quint16 _number;
27 
28   public slots:
29     void onConnected() {
30         subscribe("qmqtt/exampletopic", 0);
31         _timer.start(1000);
32     }
33 
34     void onTimeout() {
35         QMQTT::Message message(_number, "qmqtt/exampletopic",
36                                QString("Number is %1").arg(_number).toUtf8());
37         publish(message);
38         _number++;
39 //        if(_number >= 10) {
40 //            _timer.stop();
41 //            disconnectFromHost();
42 //        }
43     }
44 
45     void onDisconnected() {}
46 };
47 
48 #endif // PUBLISHER_H

 

Qt - QMQTT订阅者和发布者

上一篇:C# 波浪线绘制


下一篇:Django框架rest_framework中APIView的as_view()源码解析、认证、权限、频率控制