
大家知道,微信小程序的websocket API他们自己定制了,这样一些运行在浏览器里的库默认是运行不了的,比如mqttjs这个库:https://github.com/mqttjs/MQTT.js
由于搜狗公司兄弟团队的一个微信小程序要跑mqtt协议,我研究了下,结果如下:
第一步:
参考此库官方说明:https://github.com/mqttjs/MQTT.js#browserify
npm install -g webpack // install webpackcd node_modules/mqtt npm install . // install dev dependencies webpack mqtt.js ./my_mqtt.js --output-library-target commonjs2
第二步:
将生成的my_mqtt.js文件里所有的:
(function() { return this; }())
替换为:
window
第三步:
在my_mqtt.js文件顶部加上代码:
var setImmediate = setTimeout;var clearImmediate = clearTimeout;var socketOpen = falsevar socketMsgQueue = []function sendSocketMessage(msg) { console.log('send msg:', typeof msg) console.log(msg); if (socketOpen) { wx.sendSocketMessage({ data: msg }) } else { socketMsgQueue.push(msg) }}var document = { URL: ''}var window = { setTimeout: setTimeout, clearTimeout: clearTimeout, WebSocket: function (url) { console.log('call window WebSocket', arguments) var ws = { send: sendSocketMessage, close: wx.closeSocket, onopen: null, onmessage: null, onclose: null, onerror: null } wx.connectSocket({ url: url }) wx.onSocketOpen(function (res) { console.log('收到onopen事件:', arguments) socketOpen = true for (var i = 0; i < socketMsgQueue.length; i++) { sendSocketMessage(socketMsgQueue[i]) } socketMsgQueue = [] ws.onopen && ws.onopen.apply(ws, arguments) }) wx.onSocketMessage(function (res) { console.log('收到onmessage事件:', arguments) console.log(res.data) ws.onmessage && ws.onmessage.apply(ws, arguments) }) wx.onSocketClose(function () { console.log('收到onclose事件:', arguments) ws.onclose && ws.onclose.apply(ws, arguments) }) wx.onSocketError(function () { console.log('收到onerror事件:', arguments) ws.onerror && ws.onerror.apply(ws, arguments) }) return ws; }}
var mqtt=require('../../utils/my_mqtt.js')var client = mqtt.connect('wss://workyun.com/mqtt')client.subscribe("mqtt/demo")client.on("message", function (topic, payload) { console.log([topic, payload].join(": ")) client.end()})client.publish("mqtt/demo", "hello workyun.com !")
nginx.conf:
location /mqtt { proxy_pass http://test.mosquitto.org:8080; proxy_redirect off; proxy_set_header Host test.mosquitto.org:8080; proxy_set_header Sec-WebSocket-Protocol mqtt; more_clear_headers Sec-WebSocket-Protocol; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";}
http://test.mosquitto.org:8080是mqttjs官方给搭建的一个mqtt协议测试服务器,参见:MQTT on Websocket sample
你要是有你自己的mqtt服务器,请替换成您自己的,比如activeMQ服务器。
nginx的more_clear_headers配置添加参见:openresty/headers-more-nginx-module