在vue中使用mqtt

1 篇文章 0 订阅
npm install mqtt

以下是使用mqtt的代码。需要特别注意的是:

  1. 端口是8083

  1. 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
    }
  }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值