微信小程序連接阿里雲微消息隊列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"); } }) }