主要是用vue
安装mqtt npm i mqtt
import mqtt from 'mqtt'
let client = ''
export default {
created () {
let options = {
connectTimeout: 40000,
clientId: `id`,
username: `定义的用户名`,
password: `密码`,
path: '/mqtt',
clean: true,
useSSL: true/false,
port: '端口号',
topic: '通信'
}
client = mqtt.connect(`链接的地址`, options)
this.mqttMsg()
},
methods: {
mqttMsg () {
client.on('connect', () => {
client.subscribe(`通信`, { qos: 0 }, (error) => {
if (!error) {
console.log('success')
} else {
console.log('fail')
}
})
})
// 接收消息处理
client.on('message', (topic, message) => {
let msg = message.toString()
if (msg && JSON.parse(msg).content === 'ok') {
console.log('信息成功')
}
})
client.on('reconnect', (error) => {
console.log('正在重连:', error)
})
// 链接异常处理
client.on('error', (error) => {
console.log('连接失败:', error)
})
},
}
}
网友评论