小程序支持mqtt over websocket

由于项目有一个通讯功能,使用到了mqtt。接入小程序的过程中,因小程序本身的限制,线上环境只能是https和wss的接入方式。遇到了一些问题,处理后记录下,也当做是一次分享,希望可以帮到其他的后来的人。

环境:
1、mosquitto(mqtt服务器)
2、Nginx
3、Jetty(Java应用服务器)
4、haproxy

主要是利用了Nginx反向代理功能,配置如下:
server {
listen 443 ssl;
server_name ma.minapps.com; #域名
ssl_certificate /usr/local/nginx/cert/server.pem; #(证书公钥)
ssl_certificate_key /usr/local/nginx/cert/server.key; #(证书私钥)
ssl_session_timeout 5m;
ssl_protocols SSLv2 SSLv3 TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
ssl_prefer_server_ciphers on;
charset utf-8;
access_log logs/ma/access.log;
error_log logs/ma/error.log;
location /{
proxy_pass http://jetty.minapps.com; #代理到原有的http的地址去,格式为(http://ip:prot或http://域名)
proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header Access-Control-Allow-Origin *;#跨域访问设置
}

location /wss {
proxy_pass http://websocket.minapps.com:9001; #对应的mqtt服务器的地址,websocket的端口
proxy_redirect off;
proxy_set_header Host websocket.minapps.com;
proxy_connect_timeout 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
proxy_set_header Sec-WebSocket-Protocol mqtt;
more_clear_headers Sec-WebSocket-Protocol;
proxy_http_version 1.1;
proxy_set_header Upgrade “websocket”;
proxy_set_header Connection “upgrade”;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}

这里写图片描述

过程如上图:其中haproxy主要配置如下:(主要是监听过来的443端口转发到对应的服务器上)
frontend https_frontend
bind *:443
mode tcp
default_backend httpsserver

backend httpsserver
mode tcp
balance roundrobin
stick-table type ip size 200k expire 30m
stick on src
server s1 ip:prot #对应的Nginx地址和端口;

因环境的一些原因,加入了haproxy,其实上haproxy可以去掉,主要是根据实际情况而定。
另外,因前期没有用Nginx代理的处理方式,Jetty应用服务器和mqtt服务器实际上都已经分别支持了https和wss的协议方式。所有才会上图中看到了http/https和ws/wss的情况。

另:
添加后会出现:
nginx: [emerg] unknown directive “more_clear_headers” in /usr/local/nginx/conf/nginx.conf:374
解决方法详见:Nginx新增模块more_clear_headers

js客户端测试地址:
http://mitsuruog.github.io/what-mqtt/

小程序客户端库采用了:Paho.MQTT

参考资料:
http://blog.csdn.net/chopin407/article/details/52937645
http://blog.csdn.net/qcloud0755/article/details/52671281
https://zhuanlan.zhihu.com/p/24823848
https://segmentfault.com/q/1010000008993449
http://www.wxappclub.com/topic/842

猜你喜欢

转载自blog.csdn.net/fengaodlw/article/details/79270495
今日推荐