微信小程序连接MQTT服务器、阿里云微消息队列MQTT版
微信小程序连接阿里云微消息队列MQTT版,(多看几遍文档)
https://help.aliyun.com/document_detail/59721.html
连接的参数:
1. client id (GID_XXX@@@YYY)
2. 用户名 (Signature|xxx|xxx)
3. 密码(根据阿里云规则计算,使用 hex_hmac_sha1.js 计算)
4. const client = mqtt.connect('wx://xxx.mqtt.aliyuncs.com', options)
5. 关于topic,主topic例如‘test’,子topic可以是‘test/test2’
打开 https://unpkg.com/browse/mqtt@2.18.8/dist/mqtt.min.js 复制保存为js文件并且引入该文件
const mqtt = require('../../utils/mqtt.min.js')
function connectMqtt() { const options = { connectTimeout: 30000, keepalive: 120, clientId: '12345678', username: 'xxx', password: 'xxx', } const client = mqtt.connect('wxs://x.x.x.x', options) client.on('reconnect', (error) => { console.log('mqtt on reconnect:', error) }) client.on('disconnect', (e) => { console.log('mqtt on disconnect') }) client.on('error', (error) => { console.log('mqtt on error:', error) }) client.on('connect', (e) => { console.log('mqtt on connect') client.subscribe('test', { qos: 0 }, function (err) { if (!err) { console.log("mqtt sub success") } }) }) client.on('message', function (topic, message, packet) { var payload = packet.payload.toString() console.log("mqtt on message:", payload) if (payload == 'server_cmd_send_test') { client.publish('test2', "send_test from minip"); } }) }
境随心转而悦,心随境转而烦