MQTT连接小程序实时消息监测

参考:http://t.zoukankan.com/emqx-p-15224292.html

根据自己的需求改了一下

MQTT.js CDN 地址:https://unpkg.com/mqtt@4.0.1/dist/mqtt.min.js

在 utils 文件夹下新建一个 mqtt.min.js 文件,将cdn里的代码复制进来

在需要监测消息的页面引入 mqtt.min.js

页面的.js文件

import mqtt from "../../utils/mqtt.min.js";

Page({
  data: {
    // mqtt连接参数
    client: null,
    host: 'broker.emqx.io:8084', //地址
    topic: 'testtopic/miniprogram', //主题
    msg: 'Hello! I am from WeChat miniprogram',
    mqttOptions: {
      protocolVersion: 4, //MQTT连接协议版本
      clientId: 'emqx_cloud_miniprogram',
      clean: true,
      password: '',
      username: '',
      reconnectPeriod: 1000, // 1000毫秒,两次重新连接之间的间隔
      connectTimeout: 30 * 1000, // 1000毫秒,两次重新连接之间的间隔
      resubscribe: true // 如果连接断开并重新连接,则会再次自动订阅已订阅的主题(默认true)
    },
  },
  // 连接
  connect() {
    // MQTT-WebSocket 统一使用 /path 作为连接路径,连接时需指明,但在 EMQX Cloud 部署上使用的路径为 /mqtt
    // 因此不要忘了带上这个 /mqtt !!!
    // 微信小程序中需要将 wss 协议写为 wxs,且由于微信小程序出于安全限制,不支持 ws 协议
    try {
      this.data.client = mqtt.connect(`wxs://${this.data.host}/mqtt`, this.data.mqttOptions)
      this.data.client.on("connect", () => {
        console.log('mqtt连接成功')
        // 开启订阅
        this.subscribe()
        // 接收消息
        this.data.client.on("message", (topic, message) => {
          console.log('mqtt接收消息成功')
          wx.showModal({
            content: `${message.toString()}`,
            showCancel: false,
            success (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          });
        });
        this.data.client.on("error", (error) => {
          console.log("onError", error);
        });
  
        this.data.client.on("reconnect", () => {
          console.log("reconnecting");
        });
  
        this.data.client.on("offline", () => {
          console.log("onOffline");
        });
        // 更多 MQTT.js 相关 API 请参阅 https://github.com/mqttjs/MQTT.js#api
      });
    } catch (error) {
      console.log("mqtt.connect error", error);
    }
  },
  // 订阅主题
  subscribe() {
    if (this.data.client) {
      this.data.client.subscribe(this.data.topic);
      console.log(`成功订阅主题:${this.data.topic}`)
      return;
    }
  },
  // 取消订阅
  unsubscribe() {
    if (this.data.client) {
      this.data.client.unsubscribe(this.data.topic);
      console.log(`成功取消订阅主题:${this.data.topic}`)
      return;
    }
  },
  // 断开连接
  disconnect() {
    this.data.client.end();
    this.data.client = null;
    console.log('mqtt成功断开连接')
  },
   /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  	// 进入页面开始连接
  	this.connect();
  }
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  	//退出页面取消订阅,断开连接
    this.unsubscribe()
    this.disconnect()
  },
});
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值