Note: Here is an example using Ali Cloud MQTT. Note: The user name and password below must be transmitted in accordance with the requirements of aliyun official documents; otherwise, authentication will fail and messages cannot be sent. (The user name and password can be connected without input, but it is a fake connection. It is estimated that ali Cloud official hid the failure hint, so the front end will not report an error, but ali cloud background can not find any message record, and it shows that the client is not online)
App.js // introduce MQTT const MQTT = require('utils/mqtt.min.js') const CryptoJS = require('./utils/corty.js') // generate random strings, Because clientId if you set it to a fixed string, when you compile the // code you will connect to the server with this ID, when you preview or debug the real machine it will be the same // ID, ID occurs the problem of conflict. The function randomString (len) {len = len | | 32; var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; var maxPos = $chars.length; var pwd = ''; for (let i = 0; i < len; i++) { pwd += $chars.charAt(Math.floor(Math.random() * maxPos)); } return pwd; } // Connect to the server domain name, pay attention to format!! const host = 'wxs://post-cn-31t1ncmf90c.mqtt.aliyuncs.com/mqtt'; Const accessKey = 'LTAI4G2Mr2NE45UYbRE3bsEi' // SecretKey, Const instanceId = 'post-cn-31t1ncmf90c' // instanceId, Topic + "/p2p/" + clientId const topic = 'tml_cmd' // The parent topic needs to apply const secretKey = in the console 'wssi4k3SbC7IE4xP6pko3hHhN78Svc / / account SecretKey, Const groupId = 'GID_tml_cmd' // MQTT groupId = const clientId = '@@@xiaoming'; // GroupId @@@deviceid, which consists of a Group ID created by the console and a Device ID specified by the console. Const options = {protocolId: "MQTT", protocolVersion: 4, //MQTT connection protocolVersion clientId: GroupId + '@@@xiaoming', // groupId @@@@deviceid; RandomString (10), // Generate ID randomly, clean: true, // set to false to receive previous subscriptions while offline, true to ignore previous offline messages reconnectPeriod: ConnectTimeout: 30 * 1000, // 1000 ms, connectTimeout: 30 * 1000, // 1000 ms, connectTimeout: 30 * 1000, // 1000 ms, resubscribe: True, / / if the connection disconnect and reconnect, will automatically subscribe again has been the theme of the subscription (default true) the username: 'Signature |' + + '|' the accessKey + instanceId, password: CryptoJS.HmacSHA1(clientId, secretKey).toString(CryptoJS.enc.Base64) } // app.js App({ data: {// Count reconnectCounts: 0,}, onLaunch() {// Initialize MQTT const client = mqtt.connect(host, options); This.globaldata. client = client // Start connecting to client.on('connect', (e) => {console.log(' Successfully connect to server! ') this.globalData.topic = topic; }) // reconnect client. On ('reconnect', (error) => {console.log(' reconnect', 'error')}) // Reconnect client. (error) => {console.log(' connection failed :', error)}) // The server sends a message to the callback client. Packet) => {this.globaldata.mqttData = packet.paypay.tostring ()}) Client. Subscribe (Topic, {qos: 0},(err) => {if (! Err) {console.log(' message subscribed successfully '+ err)} else {wx.showtoast ({title:' subscribed topic failed ', icon: 'fail', duration: Client. Unsubscribe (topic) // Subscribe message type // Client. Subscribe ({// 'Tips1': {// qos: 0 // }, // 'Tips2': { // qos: 1 // } // },function(err) { // if(! Err) {/ / wx. ShowToast ({/ / title: 'subscription theme more successful / /}) / /} else {/ / wx. ShowToast ({/ / title:' subscription theme more failure ', / / icon: 'fail', // duration: // unsubscribe(['Tips1', 'Tips2']) // unsubscribe(['Tips1', 'Tips2']) // client.publish(topic, 'Hello MQTT) / / show the local storage capacity const logs. = wx getStorageSync (' logs') | | [] logs. The unshift (Date. Now ()) Wx. setStorageSync('logs', logs) // Wx. login({success: OpenId, sessionKey, unionId}})}, globalData: {userInfo: null, mqttData: null, client: MQTT // index.js // getApp() const app = getApp() Page({data: {}, // event handler onLoad() {}, sendMsg() { // console.log(app) const client = app.globalData.client const topic = app.globalData.topic if (client && client.connected) { client.publish(topic, 'i am from wechat msg') wx.showToast({ title: } else {wx.showtoast ({title: 'please connect to server first ', icon:' None ', duration: 2000})}})Copy the code
Below are the two libraries used in the documentation.
-
mqtt.min.js
www.aliyundrive.com/s/ZfZ3a1sn9…
-
corty.js
alywp.net/1ByeqP