1、下载mqtt插件
因为网页不支持mqtt直接通信,所以我们要借助插件实现:
npm install mqtt -save
2、在项目中引入mqtt
本人下载的为5.0.5版本:
import * as mqtt from 'mqtt/dist/mqtt'
3、创建mqtt链接
创建连接时,mqttUrl必须使用ws连接地址,如: ws://xxx.xxx.x.xxx:8083/mqtt,ws连接端口号默认为8083,无特殊情况就使用该端口(我在开发的时候后端提供的是映射出来的端口,死命连接不上)
createConnection () {
try {
// mqttUrl为后端搭建的mqtt服务地址,
// mqttOptions为配置信息(用户名,密码...),
// clientId 为唯一id,不能重复
this.client = mqtt.connect(mqttUrl, { ...mqttOptions, clientId })
if (this.client.on) {
this.client.on('connect', () => {
console.log('连接成功!')
})
this.client.on('error', error => {
console.log('连接失败', error)
})
this.client.on('message', (topic, message) => {
// this.receiveNews = this.receiveNews.concat(message)
console.log(`收到的消息 ${message} 来自主题 ${topic}`)
}
})
}
} catch (error) {
this.connecting = false
}
},
// 订阅mqtt主题
doSubscribe (topic, qos) {
this.client.subscribe(topic, { qos }, (error, res) => {
if (error) {
console.log('订阅主题错误', error)
return
}
},
// 发布消息
doPublish (topic, payload) {
this.client.publish(topic, payload, 2, error => {
if (error) {
console.log('消息发布错误', error)
}
})
},
// 取消订阅
doUnSubscribe () {
const { topic } = this.subscription
this.client.unsubscribe(topic, error => {
if (error) {
console.log('取消订阅错误', error)
}
})
},
// 断开链接
destroyConnection () {
if (this.client.connected) {
try {
this.client.end(false, () => {
this.initData()
console.log('已成功断开连接!')
})
} catch (error) {
console.log('断开连接失败', error.toString())
}
}
},
要实现通信,需要先订阅主题,后续在订阅的主题有消息后,通过就会在下面这个位置打印,message:收到的消息也就是数据来自主题topic(订阅的主题)
前端也可已发布消息到mqtt服务器:
// 发布消息
doPublish (topic, payload) {
this.client.publish(topic, payload, 2, error => {
if (error) {
console.log('消息发布错误', error)
}
})
},
topic为你需要发布的主题,payload为发布的消息内容
4、mqtt流程
🌹欢迎大家留言交流,说得不对之处,欢迎各位大佬批正,转发
请注明出处,谢谢支持!🌹
🌹 觉得有帮助可以点个关注哦🌹