安装依赖

npm install mqtt@2.18.9 --save

代码集成

JS工具
mqtt-utils.js

import mqtt from "mqtt";

export default {
MQTT_SERVER: "ws://XXXXXXX:8083/mqtt",//ws的端口是8083 TCP端口是1883
MQTT_CONFIG: {
username: "XXXX",
password: "XXXXX",
clientId: "WEB_01",
keepAlive: 60,
cleanSession: true,
clear: true
},
mmClient: null,

handleCon(clientId) {
console.log('==handleCon==');
this.mClient = mqtt.connect(this.MQTT_SERVER, this.MQTT_CONFIG);

// mqtt连接
this.mClient.on("connect", (e) => {
console.log(e, "mqtt连接成功!");
let topic1 = "device/+/send";
// // let topic2 = "test2";
let qos1 = 0;
// // let qos2 = 0;
// this.subTopic(this.mClient, [topic1, topic2], [qos1, qos2]);
this.subTopic([topic1], [qos1]);

});

// 消息处理
this.mClient.on("message", (topic, message) => {
console.log("收到消息", topic, message);
// let value = message.buffer
var uint8_msg = new Uint8Array(message);
var message = String.fromCharCode.apply(null, uint8_msg);
console.log(message);
})

// 断线重连
this.mClient.on("reconnect", (error) => {
console.log("正在重连:", new Date().getTime(), error);
})

// 连接失败
this.mClient.on("error", (err) => {
console.log("mqtt连接失败!{}", err);
this.mClient.end();
})


},

/**
* 【通用】发布话题
*
* @param mClient
* @param topic
* @param qos
* @param msg
*/

pubTopic(topic, qos, msg) {
console.log('=======pubTopic=====')
this.mClient.publish(topic, msg, qos, err => {
if (!err) {
console.log("发布成功!");
} else {
console.log("发布失败!", err);
}
})
},


/**
* 【通用】订阅话题
*
* @param mClient
* @param topic
* @param qos
*/
subTopic(topic, qos) {
this.mClient.subscribe(topic, qos, err => {
if (!err) {
console.log("订阅成功!");
} else {
console.log("订阅失败!", err);
}
})
}
}

VUE页面集成

this.initMqtt();
MqttUtils.pubTopic("device/123456789/recive", 1, "123123");