前端通过MQTT与后端进行数据通信

1、下载mqtt插件

  因为网页不支持mqtt直接通信,所以我们要借助插件实现:

npm install mqtt -save

2、在项目中引入mqtt

  本人下载的为5.0.5版本:

import * as mqtt from 'mqtt/dist/mqtt'

3、创建mqtt链接

   创建连接时,mqttUrl必须使用ws连接地址,如: ws://xxx.xxx.x.xxx:8083/mqtt,ws连接端口号默认为8083,无特殊情况就使用该端口(我在开发的时候后端提供的是映射出来的端口,死命连接不上)

createConnection () {
      try {
        // mqttUrl为后端搭建的mqtt服务地址,
        // mqttOptions为配置信息(用户名,密码...),
        // clientId 为唯一id,不能重复
        this.client = mqtt.connect(mqttUrl, { ...mqttOptions, clientId })
        if (this.client.on) {
          this.client.on('connect', () => {
            console.log('连接成功!')
          })
          this.client.on('error', error => {
            console.log('连接失败', error)
          })
          this.client.on('message', (topic, message) => {
            // this.receiveNews = this.receiveNews.concat(message)
            console.log(`收到的消息 ${message} 来自主题 ${topic}`)
            }
          })
        }
      } catch (error) {
        this.connecting = false
      }
    },
    // 订阅mqtt主题
    doSubscribe (topic, qos) {
      this.client.subscribe(topic, { qos }, (error, res) => {
        if (error) {
          console.log('订阅主题错误', error)
          return
        }
    },
    // 发布消息
    doPublish (topic, payload) {
      this.client.publish(topic, payload, 2, error => {
        if (error) {
          console.log('消息发布错误', error)
        }
      })
    },
    // 取消订阅
    doUnSubscribe () {
      const { topic } = this.subscription
      this.client.unsubscribe(topic, error => {
        if (error) {
          console.log('取消订阅错误', error)
        }
      })
    },
    // 断开链接
    destroyConnection () {
      if (this.client.connected) {
        try {
          this.client.end(false, () => {
            this.initData()
            console.log('已成功断开连接!')
          })
        } catch (error) {
          console.log('断开连接失败', error.toString())
        }
      }
    },

要实现通信,需要先订阅主题,后续在订阅的主题有消息后,通过就会在下面这个位置打印,message:收到的消息也就是数据来自主题topic(订阅的主题)

前端也可已发布消息到mqtt服务器: 

// 发布消息
    doPublish (topic, payload) {
      this.client.publish(topic, payload, 2, error => {
        if (error) {
          console.log('消息发布错误', error)
        }
      })
    },

topic为你需要发布的主题,payload为发布的消息内容

4、mqtt流程

 🌹欢迎大家留言交流,说得不对之处,欢迎各位大佬批正,转发请注明出处,谢谢支持!🌹

 🌹 觉得有帮助可以点个关注哦🌹

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值