微信小程序、H5连接MQTT服务实践

一个LOT项目,微信小程序控制开关的产品。搞了半天,查阅各种资料,终于搞掂,有些坑必须填写一下。

1.首先是MQTT的文件和版本问题。一定要用4.0.1版本。官网地址:https://unpkg.com/mqtt@4.0.1/dist/mqtt.js

刚开始一直用最新版,各种问题调试不通过。

2.小程序的写法。在小程序里,写法跟H5是不一样的(就这个问题也搞了好久…………)

 不说了,说多了是泪,直接上代码:

// 引用下载好的mqtt文件
const mqtt = require('../../utils/mqtt');
Page({
  data: {
    clientMqtt:null,
  },
   onLoad(option){
     this.initMQTT()
   },
   initMQTT(){
     const that = this
        // 连接选项
    const options = {
      clean: true, // true: 清除会话, false: 保留会话
      connectTimeout: 10000, // 超时时间
      // 认证信息
      clientId: 'wechat_' + Math.random().toString(16).substr(2, 8),
      username: 'xxxx', //连接用户名
      password: 'xxxx',//连接密码
      // 心跳时间
      keepalive: 60,
      protocol: "wx", //这一条很重要,就是卡在这里收不了消息
      port:54001
    }
    that.data.clientMqtt = mqtt.connect('ws://xxx.com', options)
    that.data.clientMqtt.on('connect', (e) => {
      console.log('成功连接服务器')
      //订阅一个主题
      const topic = "jimmy1993";
      that.data.clientMqtt.subscribe(topic, { qos: 0 }, (err) => {
        if (!err) {
          that.data.clientMqtt.publish(topic, 'Hello mqtt')
         console.log(topic + "订阅成功")
        }
       })
      })
      //监听mq的返回
    that.data.clientMqtt.on('message', (topic, message) => {
        let msg = message.toString();
        console.log('收到消息:', topic, message.toString())
        //that.data.clientMqtt.end()
    })
    that.data.clientMqtt.on('reconnect', (error) => {
      console.log('正在重连:', error)
    });
    that.data.clientMqtt.on('error', (error) => {
      console.log('连接失败:', error)
    });
   }

消息发布接收,如下图:

 

 

 完美!

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赚成美业

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值