微信小程序+MQTT

未结帖
0 869
ajian lucy 2017-03-03
悬赏:5飞吻

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

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

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

第一步:

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

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

二、微信小程序里调用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


热忱回答0


最近热帖

近期热议

  1. javascript——prototype与__proto 9
  2. Mysql 中出现的Data truncated for column 3
  3. 在nginx中使用x-sendfile的解决方案 3
  4. 高版本jQuery面插件实现Ajax上传图片 1
  5. Thinkphp Socket.class.php 类的使用 1
  6. 使用ionic3创建第一个App 0
  7. ios-oc html5 0
  8. nginx.conf 0
  9. 基于ionic3.4.0的项目搭建 0
  10. php 缩略图 0