一、安装依赖
npm install [email protected]
注意要指定下载3.0.0版本
二、废话少说直接上代码
1. main.js全局注册MQTT
代码如下(示例):
const MQTT = require('mqtt/dist/mqtt.js')
Vue.prototype.$MQTT = MQTT; //挂载在 Vue 实例上
2. 调用
我用的nvue,而且没有全局需求,并没有把MQTT连接注册到全局,根据自身需求,以下仅为示例
代码如下(示例):
// 引入MQTT
const MQTT = require('mqtt/dist/mqtt.js')
// 声明client
data(){
return {
client: null
}
}
// 连接方法
methods: {
MQTTINIT(){
let options = {
username: '',
clientId: '',
connectTimeout: 600000,
keepalive: 5, // 心跳,单位秒,如果后台开启监听可以快速知道有没有退出
clean: true,
// password: '',
// reconnectPeriod: 5000,
}
// 订阅 topic。如果订阅多个 var subscribe = ["test1","test2"]
var subscribe = "test"
if(this.client){
this.client.end()
}
// #ifdef APP-PLUS
this.client = MQTT.connect('wx://xxxxxxxxxxx:xxxx/mqtt',options)
// #endif
// #ifdef H5
this.client = MQTT.connect('ws://xxxxxxxxxxx:xxxx/mqtt',options)
// #endif
this.client.on('connect', (res)=>{
console.log(res,1111);
uni.hideLoading()
uni.showToast({
title:"连接成功",
duration:2000,
icon:"none"
})
this.client.subscribe(subscribe , (err)=>{
console.log(err,2222);
if (!err) {
uni.showToast({
title:"订阅成功",
duration:2000,
icon:"none"
})
}
})
}).on('message', (topic, message)=>{
console.log(topic,message)
}).on('reconnect', (topic, message)=>{
uni.showLoading({
title: '重连中...'
})
console.log("重连")
}).on('error',()=>{
//重新连接
client.reconnect()
})
// close: function () {} 断开连接回调
// offline : function () {} 客户端离线回调
// 发送,
// this.client.publish('system','hello',{},(res)=>{
// console.log(res)
// })
// system: topic订阅的主题,第二个参数发送内容Buffer or String类型(可以转成JSON字符串JSON.stringify()),第三个参数[options]看下方【不必填】,第四个回调【不必填】
// qos QoS 等级, Number, default 0
// retain 保留消息标志, Boolean, default false
// dup 重复标志, Boolean, default false
}
}