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

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

1.首先是MQTT的文件和版本问题。一定要用4.0.1版本。官网地址:https://unpkg.com/[email protected]/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)
    });
   }

消息发布接收,如下图:

 

 

 完美!

猜你喜欢

转载自blog.csdn.net/hzmpkpkppk/article/details/124296587