小程序, 网络

Megalo 中使用mqtt

By jere on 2019-07-08 0 Comments

webpack 打包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

请参考这里

Client

var mqtt = require('#/libs/mqtt')
const client = mqtt.connect(config.chat_server, {
clean: false,
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8)
})

this.client.subscribe('driver')
this.client.on('message', function(topic, message) {
const data = JSON.parse(message.toString())
// ...
})

Nginx 配置

location / {
proxy_set_header Host $http_host;
proxy_pass http://yourserver:8083;
proxy_set_header Sec-WebSocket-Protocol mqtt;
proxy_http_version 1.1;
proxy_set_header X-Client-IP $remote_addr;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}

URL

微信小程序为 wx 或 wxs,并不是 ws 或 wss

打赏

Leave a comment

您的电子邮箱地址不会被公开。 必填项已用 * 标注