1.MQTT服务器端下载安装mosquitto
2.MQTT客户端 QT版
1.MQTT服务器端下载安装mosquitto
1.1安装服务器端
sudo apt-get install mosquitto
1.2安装客户端
sudo apt-get install mosquitto-clients
1.3安装设备端
sudo apt-get install mosquitto-dev
1.4修改配置文件
cd /etc/mosquitto
vim mosquitto.conf

- allow_anonymous false #表示不可以匿名访问
- password_file /etc/mosquitto/pwfile.example #用户和密码放在pwfile.example
1.5重启服务
service mosquitto restart
1.6访问
- #1.客户端:访问本地,用户名:test ;密码:123@123;主题:11
- mosquitto_sub -h localhost -p 1883 -u test -P 123@123 -t "11"
-
-
- #2.服务器端可以查看到一个连接
- lsof -i | grep mosquitto
-
-
- #3.服务器端发布
- mosquitto_pub -h localhost -p 1883 -u test -P 123@123 -t "11" -m "helloworld"
-
- #此时客户端可以看到发布了
-
2.QT版的MQTT客户端
2.1环境配置:
下载 https://github.com/qt/qtmqtt/tree/5.15
配置:项目->配置
双击.pro文件做配置
常见问题:
1.没有头文件:
把头文件复制后放入QT的安装目录下。文件夹名称位QtMqtt
D:\ProgramData\Qt\Qt5.14.2\5.14.2\mingw73_32\include\
2.编译后出错:
修改成:
- connect(socket, static_cast<void(QAbstractSocket::*)(QAbstractSocket::SocketError)> (&QAbstractSocket::error),
- this, static_cast<void(QMqttConnection::*)(QAbstractSocket::SocketError)>(&QMqttConnection::transportError) );
3.复制被编译好的两个文件:bin目录下:Qt5Mqtt.dll,Qt5Mqttd.dll
复制后放入QT的安装目录下 D:\ProgramData\Qt\Qt5.14.2\5.14.2\mingw73_32\bin
2.2第一个demo程序:
1.pro文件设置:network
- #1.添加core
- QT += core gui network
-
-
- #2.添加lib
- LIBS +=D:\QTPrj\MQTT\build-qtmqtt-Desktop_Qt_5_14_2_MinGW_32_bit-Debug\lib\Qt*.dll

2..h文件
- #include
- {
- private slots:
- void on_connectButton_clicked():
- void connectSuccessSolt(); //连接成功
- void recvMessageSolt();
- private:
- QMqttClient *client;
- }
3.cpp文件
- #include
-
- Widget::~Widget()
- {
- ui->setupUi(this);
- client=new QMqttClient;
- client->setHostname("");
- client->setPort(1883);
- client->setUsername("test");
- connect(client,&QMqttClient::connected,this,&Widget::connectSuccessSlot);
- }
- //1.开始连接服务器
- void Widget::on_connectButton_clicked()
- {
- client->connectToHost();
- }
- //连接成功
- void Widget::connectSuccessSlot()
- {
- QMessageBox::information(this,"连接提示","连接成功"); connect(client,&QMqttClient::messageReceived,this,&Widget::recvMessageSolt);
- connect(client,&QMqttClient::disconnected,[this](){
- QMessageBox::warning(this,"连接提示","服务器断开");
- });
- }
- //处理消息
- void Widget::recvMessageSolt(const QByteArray &ba,const QMqttTopicName &topic)
- {
- QString str= topic.name()+QString(ba);
- ui->textEdit->setText(str);
- }
- //订阅
- void Widget::on_subButton_clicked()
- {
- client->subscribe(ui->subTopicEdit->text());
- }
- //发布
- void Widget::on_pubButton_clicked()
- {
- QString msg=ui->msgEdit->text();
- QByteArray ba;
- ba.append(msg);
- client->publish(ui->pubTopicEdit->text(),ba);
- }
3. openssl 里添加 两个库。
