The file import
MQTT. Js CDN: unpkg.com/[email protected]/…
The files are placed in the applet directory and the MQTT is imported
var mqtt = require('./utils/mqtt')
Copy the code
Initialization file
The development environment can use THE WS protocol, the formal environment must use the WSS protocol.
let url = wx://xxxxxxx.cn:8084/mqtt
let client = mqtt.connect(url, {
clientId: 'wqs' + date, // Client ID
username: 'web'./ / user name
password: 'Web2020qaz'./ / password
// The port can be written in the URL or in the configuration item
port: 8084 / / port
})
this.globalData.client = client
Copy the code
Define a global variable in the applet app.js file to hold the MQTT connection
globalData: {
client: null
}
Copy the code
Listen for MQTT phase events. Normally, the first connection will go into a successful connection callback, and the client will be reconnected if special circumstances occur
client.on('connect'.(e) = > {
console.log("Connection successful")
})
client.on('error'.(error) = > {
console.log("Client error: error =", error);
});
client.on('reconnect'.() = > {
console.log("Reconnection occurred!");
});
client.on('offline'.() = > {
console.log("Client offline!");
});
Copy the code
Listening for subscription messages
news
client.publish('123'.'Hello mqtt')
Copy the code
Subscribe to news
client.subscribe('Specific subject address', {
qos: 0
}, (err) = > {
if(! err) {console.log("Subscription successful")}})Copy the code
Parse (message.tostring ()) const data = json.parse (message.tostring ())
client.on('message'.(topic, message) = > {
this.handleMeeage(topic, message)
})
Copy the code
Android and IOS compatibility issues
In ios environment, address wx: / / XXXXXXX. Cn: 8084 / MQTT can normal send and receive messages, in the android environment connection fails, found that after the access to a lot of data need to the proxy to the default port, port to wx: / / XXXXXXX. Cn/MQTT, android can run normally.