概述
npm install mqtt
以下是使用mqtt的代码。需要特别注意的是:
端口是8083
mqtt.connect的url协议是"ws",而且后面要跟"/mqtt"
import mqtt from 'mqtt'
mounted () {
const options = {
clean: true,
connectTimeout: 4000,
clientId: 'test',
username: 'xxx',
password: 'xxx',
keepalive: 60,
port: 8083
}
this.client = mqtt.connect('ws://xxx.com/mqtt', options)
this.client.on('connect', e => {
console.log('连接成功', e)
this.client.subscribe('xxx', (err) => {
if (!err) {
console.log('订阅成功:' + 'xxx')
}
})
})
this.client.on('message', (topic, message) => {
console.log(topic + '返回的数据:' + message.toString())
let data = this.canParseToJson(message.toString())
if (data) {
this.msg = JSON.parse(message.toString())
}
})
this.client.on('reconnect', (error) => {
console.log('正在重连:' + error)
})
this.client.on('error', (error) => {
console.log('连接失败:' + error)
})
},
methods: {
mqttPublish: function (pid = 0) {
console.log('mqttPublish', pid)
this.client.publish(this.mtopic, {pid: pid})
},
canParseToJson (str, parseFlag = true) {
try {
if (typeof JSON.parse(str) === 'object' && Object.prototype.toString.call(JSON.parse(str)) === '[object Object]') {
return parseFlag === true ? JSON.parse(str) : true
}
} catch (e) {}
return false
}
}
最后
以上就是勤劳书本为你收集整理的在vue中使用mqtt的全部内容,希望文章能够帮你解决在vue中使用mqtt所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复