微信小程序整合MQTT

本文整理微信小程序整合MQTT开发所需要步骤和注意事项.

在本文的第一版时已经使用多终端测试过功能是OK的,没想到上线时却发现Android端不可用有点摸不着头脑……多想无益只能继续探索……好在微信社区论坛找到了一些相同的案例,借用各位的思路重新调整了一下文章。本文并没有把原文删除,而是在最后追加一章,为了记录历史过程。

参考:

https://developers.weixin.qq.com/community/develop/doc/000c226e034c8843276ae477f52800?_at=1602948590825

https://blog.csdn.net/weixin_42306858/article/details/95307967

 

下载以下组件

MQTT Broker

杭州一家公司开发的EMQX,部署非常简单,功能强大。目前评估了免费版本功能还够用。

https://www.emqx.io/cn/downloads

 

JS客户端库

一个非常强大的千星+的MQTT js客户端,

Github: https://github.com/mqttjs/MQTT.js

很贴心还提供了CDN:

https://unpkg.com/mqtt@3.0.0/dist/mqtt.min.js

https://unpkg.com/mqtt@3.0.0/dist/mqtt.js

 

 Nginx

web服务器,本文用于反向代理。

http://nginx.org/en/download.html

 

微信小程序开发环境

微信开发工具设置

下载个VS Code吧...微信开发工具体验实在是抱歉。微信开发工具只作为调试工具使用。

https://code.visualstudio.com/Download

 

使用Linux的朋友推荐wxdt,体验非常不错,记得装wine,不然是没法调试的。

https://github.com/cytle/wechat_web_devtools

 

开发环境把"不要验证域名..."勾上,绕开云服务器,域名,证书这些部署才需要的东西。

引入MQTT.js

从上面的CDN下载拷贝里面的代码一个到小程序项目下/utils/mqtt.js

 

MQTT小样

  • 依赖
var mqtt = require('../../utils/mqtt.js');
//一个全局变量...
var client = null;

 

  • 创建连接

注意:实测以下配置仅在模拟器中或IOS真机中有效,对于Android真机并不起作用。

重点注意一下options里面的那个port,估计若是没人告诉你得扑腾一会。mqtt.js默认会通过443端口建立Web Socket连接,如果你像我一样用的是EMQX那么你需要指定端口。

协议用wx(ws)就好了,毕竟实在开发机调试用的先别搞那么复杂的。

 

connectMqtt: function() {
        const options = {
            connectTimeout: 4000, // 超时时间
            clientId: 'wx_' + parseInt(Math.random() * 100 + 800, 10),
            port: 8083,  //重点注意这个,坑了我很久
            // username: 'xxx',
            // password: 'xxx',
        }
 
        client = mqtt.connect('wx://{你的IP地址}/mqtt', options)
        client.on('reconnect', (error) => {
            console.log('正在重连:', error)
        })

        client.on('error', (error) => {
            console.log('连接失败:', error)
        })

        let that = this;
        client.on('connect', (e) => {
            console.log('成功连接服务器')
       //订阅一个主题 client.subscribe('message.queue', { qos: 0 }, function(err) { if (!err) { console.log("订阅成功") } }) }) client.on('message', function (topic, message) { console.log('received msg:' + message.toString()); }) },

如果上一步你可以连接上,那么恭喜你双向发送消息啦~

client.publish('message.queue', 'Hello MQTT')

 

微信部署

微信小程序上线比较严格,你的域名需要通过实名认证,还需要备案.所有的连接需要ssl加密,而且必须是认证的ca颁发的证书,如果用的是自己生成的会拒绝访问。

所以你需要走完这个流程: 开通云服务器->买域名->备案->买证书(阿里云有个人免费的symantec,有效期一年)->部署

 

MQTT Broker要开通加密Web Socket

到这里假设上面提到的你都办好了,下载证书。有很多个针对不同类型服务的证书,这里只需要下载apache那个就好了。

下载好解压出来你会得到两个文件,***.key和***_public.crt

 

  • 设置wss
listener.wss.external.keyfile = etc/certs/{你的域名}.key
listener.wss.external.certfile = etc/certs/{你的域名}_public.crt

 

  • 顺便把tcp的ssl也设置了
listener.ssl.external.keyfile = etc/certs/{你的域名}.key
listener.ssl.external.certfile = etc/certs/{你的域名}_public.crt

 

  • 重启服务,你可以通过EMQX的工具测试连接

 如果配置无误那么点击connect按钮会显示已连接。

 

 修改一下连接MQTT的代码

注意:实测以下配置仅在模拟器中或IOS真机中有效,对于Android真机并不起作用。

EMQX默认wss端口为8084,把之前的8083改为8084。

把IP地址换成域名,必须备案。

上线需要使用wss协议,所以这里把服务器协议改为wxs(wss,wxs的MQTT.js定的别问我)。

connectMqtt: function() {
        const options = {
            connectTimeout: 4000, // 超时时间
            clientId: 'wx_' + parseInt(Math.random() * 100 + 800, 10),
            port: 8084,  //重点注意这个,坑了我很久
            // username: 'xxx',
            // password: 'xxx',
        }
 
        client = mqtt.connect('wxs://{你的域名}/mqtt', options)
        client.on('reconnect', (error) => {
            console.log('正在重连:', error)
        })

        client.on('error', (error) => {
            console.log('连接失败:', error)
        })

        let that = this;
        client.on('connect', (e) => {
            console.log('成功连接服务器')
       //订阅一个主题 client.subscribe('message.queue', { qos: 0 }, function(err) { if (!err) { console.log("订阅成功") } }) }) client.on('message', function (topic, message) { console.log('received msg:' + message.toString()); }) },

 

解决 Android真机无法连接MQTT Broker问题

下载一个Nginx版本的证书,给Nginx加一个新的Server,监听端口443并代理转发EMQX的8083端口。

需要你根据实际情况修改的地方:

  • 设置域名
  • 设置证书
server {
    server_name www.{your domain}.cn;

    listen 443 ssl;
    ssl_certificate {path to cert}.pem;
    ssl_certificate_key {path to cert key}.key;
    ssl_session_timeout 5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
    ssl_prefer_server_ciphers on;
    
    location /mqtt {
        proxy_pass http://localhost:8083;
        proxy_redirect off;
        proxy_set_header Host localhost:8083;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

配套JS代码:

connectMqtt: function() {
        const options = {
            connectTimeout: 4000, // 超时时间
            clientId: 'wx_' + parseInt(Math.random() * 100 + 800, 10),
            // username: 'xxx',
            // password: 'xxx',
        }
 
        client = mqtt.connect('wxs://{你的域名}/mqtt', options)
        client.on('reconnect', (error) => {
            console.log('正在重连:', error)
        })

        client.on('error', (error) => {
            console.log('连接失败:', error)
        })

        let that = this;
        client.on('connect', (e) => {
            console.log('成功连接服务器')
       //订阅一个主题
            client.subscribe('message.queue', {
                qos: 0
            }, function(err) {
                if (!err) {
                    console.log("订阅成功")
                }
            })
        })
        client.on('message', function (topic, message) {
            console.log('received msg:' + message.toString());
        })
    },

 

OK,

转载请注明出处:https://www.cnblogs.com/keitsi/p/12571383.html

posted @ 2020-03-26 22:05  keitsi  阅读(19893)  评论(7编辑  收藏  举报