周凯,个人博客

  • 前端
  • 嵌入式
  • 工具
  • 后端
  • 随笔
个人记录
  1. 首页
  2. 前端
  3. 正文

微信小程序连接mqtt 模拟器正常使用,真机无法连接

2023年 7月 22日 661点热度 0人点赞 0条评论

问题

  • 微信小程序连接mqtt 模拟器正常使用,真机无法连接,已经配置了服务器域名

基础

  • 服务端使用的是emqx,配置域名代理8083端口
  • 微信小程序需要把wss://xx.xxx.com域名添加后台开发管理->开发设置->服务器域名,socket合法域名中

提示

由于微信小程序的规范限制,EMQX 使用微信小程序接入时需要注意以下几点:

  • 必须使用已经通过域名备案 (opens new window)的域名接入
  • 域名需要在小程序管理后台 (opens new window)域名/IP 白名单中(开发 -> 开发设置 -> 服务器域名 -> socket 合法域名)
  • 仅支持 WebSocket/TLS 协议,需要为域名分配受信任 CA 颁发的证书
  • 由于微信小程序 BUG,安卓真机必须使用 TLS/443 端口,否则会连接失败(即连接地址不能带端口)

emqx

  • nginx配置

    server
    {
    listen 80;
    listen 443 ssl http2;
    server_name 你的域名
    
    #SSL-START SSL相关配置,请勿删除或修改下一行带注释的404规则
    #error_page 404/404.html;
    ssl_certificate    你的.pem;
    ssl_certificate_key    你的.key;
    ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;
    ssl_ciphers EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    add_header Strict-Transport-Security "max-age=31536000";
    error_page 497  https://$host$request_uri;
    # 添加反向代理 ws
    location /mqtt {
      proxy_pass http://127.0.0.1:8083/mqtt;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      # client_max_body_size 35m;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";    
    }
    # 用于访问emqx页面
    location / {
      proxy_pass http://127.0.0.1:18083;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      # 默认60s断开连接
      proxy_read_timeout 60s;
    }
    }

小程序开发参考

  • 关键 mqtt版本需要是2.18.0
  • 从cdn下载文件,或者使用npm方式 npm install mqtt@2.18.0 -S
  • mqtt文件,mqtt@2.18.0
    // import mqtt from '@/utils/mqtt';
    import mqtt from 'mqtt';
    connectMqtt() {
      const {host, username, password, mcuUniqueId, pubTopic} = this.detailData;
      const connectUrl = `wxs://${host}/mqtt`
      const client = mqtt.connect(connectUrl, {
        username,
        password,
        clientId: `${mcuUniqueId}-${Date.now()}`,
        clean: false,
        reconnectPeriod: 1000, //1000毫秒,两次重新连接之间的间隔
        connectTimeout: 30 * 1000, //1000毫秒,两次重新连接之间的间隔
        resubscribe: true //如果连接断开并重新连接,则会再次自动订阅已订阅的主题(默认true)
      })
      this.mqttClient = client;
      // 服务器连接
      client.on("connect", () => {
        console.log("连接成功")
        client.subscribe(pubTopic, (err, granted) => {
          if (!err) {
            console.log("订阅成功")
            // 开启上报数据
          } else {
            console.log(`订阅${pubTopic}失败`, err)
          }
        })
      })
      //服务器连接异常的回调
      client.on("error", function (error) {
        console.log(" 服务器 error 的回调" + error)
      })
      //服务器重连连接异常的回调
      client.on("reconnect", function () {
        console.log(" 服务器 reconnect的回调")
      })
      //服务器连接异常的回调
      client.on("offline", function (errr) {
        console.log(" 服务器offline的回调")
      })
      client.on("message", (topic, message) => {
        // message is Buffer
        console.log(message.toString());
        try {
          this.subData = JSON.parse(message)
          console.log(this.subData);
        } catch (e) {
          console.error(e, '数据转换失败')
        }
    });

参考

  • EMQX MQTT 微信小程序接入
  • 在微信小程序中打造 MQTT 连接测试工具

🎯 拓展阅读提示

本文涉及的内容已同步至公众号后台,我会在那里分享更多深度内容和实用技巧

→ 点击关注:一行梦境

公众号二维码
本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: 暂无
最后更新:2023年 7月 22日

周凯

这个人很懒,什么都没留下

打赏 点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2022-现在 周凯,个人博客. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

蒙ICP备18004897号