微信小程序mqtt实现

下载mqtt到项目
方式一:
npm 在我的项目出现了奇奇怪怪的问题。所以我选择方式二
方式二:
直接下载mqtt.js
地址:https://cdnjs.com/libraries/mqtt

image.png

注意事项:若mqtt的连接的地址没有在小程序备案的话需要开启:不校验。。。。
image.png

看是否备案的位置
image.png

代码实现:
//mqttUtils

import { $GLOBAL } from '../../app';
import mqtt from './mqtt';

let client = null;
const initMqtt = function (that) {
  let url = $GLOBAL.MQTT_URL;//url:类似于:'wss://mqtt.....
  let date = new Date().getTime();
  client = mqtt.connect(url, {
    protocol: 'wxs',
    clientId: 'wqs' + date,
    username: $GLOBAL.USERNAME,//账号
    password: $GLOBAL.PASSWORD,//密码
  });
  that.globalData.client = client;//为全局client赋值:在app.js
  client.on('connect', () => {
    console.log('连接成功');
  });
  client.on('message', (topic, payload) => {
    //在这里做处理:收到新消息走这个方法
    console.log('更新', topic + ':' + payload);
  });
  client.on('disconnect', () => {
    console.log('代理断开连接');
  });
  client.on('close', () => {
    console.log('断开连接');
  });
  client.on('offline', () => {
    console.log('脱机');
  });
  client.on('error', () => {
    console.log('无法连接');
    initMqtt();
  });
};
//添加订阅 ${$GLOBAL.MQTT_TOPIC}/user/${userId}订阅的主题地址:问后端,是直接返回还是拼接
const addSubscription = function (userId) {
    client.subscribe(`${$GLOBAL.MQTT_TOPIC}/user/${userId}`, err => {
      if (!err) {
        console.log('订阅成功');
      } else {
        console.log('订阅失败');
      }
    });
  },
  mqttFun = {
    initMqtt,
    addSubscription,
  };

module.exports = mqttFun;

使用:
app.js
1、添加全局client


image.png

2、在onLaunch注册mqtt

   // 全局注册mqtt:并防止重复注册
   if (!this.globalData.client) {
     mqttUtil.initMqtt(this);
   }

在页面你想订阅的地方添加订阅方法

  mqttUtil.addSubscription(info.userId);

//其他的问题
自己测试能不能收到消息

client.publish('订阅的地址', '发送内容')
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容