网站架构
首发于网站架构

如何在微信小程序的websocket上使用mqtt协议

大家知道,微信小程序的websocket API他们自己定制了,这样一些运行在浏览器里的库默认是运行不了的,比如mqttjs这个库:github.com/mqttjs/MQTT.

由于搜狗公司兄弟团队的一个微信小程序要跑mqtt协议,我研究了下,结果如下:

一、打包出一个可以运行在微信小程序里的my_mqtt.js客户端库

第一步:

参考此库官方说明:github.com/mqttjs/MQTT.

npm install -g webpack // install webpack

cd 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 = false
var 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;
    }
}

二、微信小程序里调用my_mqtt.js

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处理微信小程序的websocket不支持HTTP头:Sec-WebSocket-Protocol问题

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";
}

test.mosquitto.org:8080是mqttjs官方给搭建的一个mqtt协议测试服务器,参见:MQTT on Websocket sample

你要是有你自己的mqtt服务器,请替换成您自己的,比如activeMQ服务器。

nginx的more_clear_headers配置添加参见:openresty/headers-more-nginx-module

编辑于 2017-01-17

文章被以下专栏收录