Vue 使用 MQTT 连接阿里云物联网平台

一、安装 mqtt 库

(网上说安装高版本容易出问题,所以安装版本为3.0.0的)

进入vue项目的根目录,然后执行安装命令:cnpm install mqtt@3.0.0 -S 

安装成功后,在 package.json 文件中可以看到 mqtt 的版本号: 

二、vue 代码实现

其中要注意 securemode 参数,使用 wss 方式连接时 securemode=2,使用 ws 方式连接时 securemode=3。(参考文章:MQTT-WebSocket连接通信 - 阿里云物联网平台 - 阿里云

<template>
  <div>
      <button @click="doConnected">连接</button>
      <button @click="doPublish">发布</button>
      <button @click="doDisconnected">断开连接</button>
      <p>收到的消息: {{recvData}}</p>
  </div>
</template>

<script>
import mqtt from 'mqtt' // 引入mqtt模块

export default {
  components: {},
  data () {
    return {
      client: null,
      options: {
        connectTimeout: 4000, // 超时时间
        clientId: 'gl9f****2vi.Car_Robot|securemode=3,signmethod=hmacsha256,timestamp=2524608000000|', // id
        username: 'Car_Robot&gl9f****2vi', // 用户名
        password: '541262081****ee538a659ca0aecc40ba7bf40861372be570e53dbdaf46fb4b9', // 密码
        cleanSession: false,
        keepAlive: 60 // 心跳值,心跳值太大可能会连接不成功,这个参考文档
      },
      subscription: {
        topic: '/sys/gl9f****2vi/Car_Robot/thing/service/property/set',
        qos: 0
      },
      publication: {
        topic: '/sys/gl9f****2vi/Car_Robot/thing/event/property/post',
        qos: 0,
        payload: ''
      },
      recvData: '' // 接收的消息
    }
  },
  methods: {
    doConnected () {
      console.log('正在连接...')
      try {
        this.client = mqtt.connect('ws://gl9f****2vi.iot-as-mqtt.cn-shanghai.aliyuncs.com:443', this.options)
      } catch (error) {
        console.log('mqtt连接失败: ', error)
      }
      this.client.on('connect', (e) => {
        console.log('连接成功')
        this.doSubscribe() // 订阅主题
      })
      // 接收消息处理
      this.client.on('message', (topic, message) => {
        console.log('收到来自', topic, '的消息', message.toString())
        this.recvData = message.toString()
      })
      // 连接错误处理
      this.client.on('error', (error) => {
        console.log('连接出错: ', error)
      })
      // 重新连接处理
      this.client.on('reconnect', () => {
        console.log('重新连接...')
      })
    },
    doDisconnected () {
      try {
        this.doUnSubscribe()
        this.client.end()
        console.log('断开连接')
      } catch (error) {
        console.log('断开连接失败: ', error.toString())
      }
    },
    doSubscribe () {
      const { topic, qos } = this.subscription
      this.client.subscribe(topic, qos, (error) => {
        if (!error) {
          console.log('订阅成功')
        } else {
          console.log('订阅失败')
        }
      })
    },
    doUnSubscribe () {
      const { topic } = this.subscription
      this.client.unsubscribe(topic, error => {
        if (error) {
          console.log('取消订阅失败', error)
        }
      })
    },
    doPublish () {
      const { topic, qos, payload } = this.publication
      this.client.publish(topic, payload, qos, error => {
        if (error) {
          console.log('发布失败', error)
        }
      })
    }
  }
}
</script>

三、测试

执行 npm run dev 命令来运行项目,如果物联网平台上对应的设备显示【在线】的状态,则连接成功!

  • 3
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值