1. 程式人生 > 其它 >微信小程式連線MQTT伺服器、阿里雲微訊息佇列MQTT版

微信小程式連線MQTT伺服器、阿里雲微訊息佇列MQTT版

微信小程式連線阿里雲微訊息佇列MQTT版,(多看幾遍文件

連線的引數:

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/[email protected]/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"); } }) }