vue安装使用mqtt

vue yekong

vue项目开发使用mqtt

安装依赖

npm i mqtt --save

引用

import mqtt from 'mqtt'

创建链接

    mqttAccessToken() {
      var that = this;
      mqttAccessToken({user: 'MAX'}).then(res => {
        var data = {
          clean: true,
          connectTimeout: 4000,
          clientId: res.data.client_id,
          username: 'MAX',
          password: res.data.token
        }
        console.log(data)
        that.client = mqtt.connect('ws://192.168.1.1:8083/mqtt', data)
        that.myMqtt()
      }).catch(err => {

      })
    },

监听

 myMqtt() {
      // 连接mqtt
      var that = this;
      that.client.on('connect', (e) => {
        console.log('连接成功')
        that.client.subscribe('subscribe')
        that.client.subscribe("screen/error/+", function (err) {
          if (!err) {
            console.log('订阅成功')
          } else {
            console.log('订阅失败')
          }
        })
      })
      // 接收推送消息
      that.client.on('message', (topic, message) => {
        console.log('接收推送信息:', message.toString())
        that.content = message.toString()
        var data = JSON.parse(message.toString())
        that.isAlert(data)
      })
      // 断开发起重连
      that.client.on('reconnect', (error) => {
        console.log('正在重连...', error)
      })
      // 链接异常处理
      that.client.on('error', (error) => {
        console.log('连接失败...', error)
      })
    }

其他问题

连接不上问题,通过mqtt在线测试工具测试一下,看看是否可以正常连接
检查地址是否正常ws://192.168.1.1:8083/mqtt,一般是ws:+ip+端口+'/mqtt'这种模式。

喜欢