微信小程序連接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"); } }) }

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM