Due to requirements, mqtt is needed in the applet to perform long connections of tcp and monitor the return status of the device in real time.
Connecting to the mqtt server in js is achieved through websocket. I found 2 libraries online, one is paho-mqtt developed by eclipse.
Project address:/eclipse/
One is a mqttjs developed by individuals, project address:/mqttjs/
After comparison, it is more flexible and has good support for mini programs, so this library is used for connection.
So he read his own introduction and took it over and tried it out. Because it is not so complicated to use directly in mini programs, it provides static CDN downloads.
Just open the link and copy it to the project and use it directly without changing it. cdn address:/[email protected]/dist/Min version:/[email protected]/dist/;
It's also very simple to use, just paste the code
function connectMq(){ // Connection options const options = { connectTimeout: 4000, // Timeout time //Certification information Fill in according to your needs clientId: '', username: 'xxx', password: 'xxx', } let phone = ; const client = ('wx://', options) ('reconnect', (error) => { ('Reconnecting:', error) }) ('error', (error) => { ('Connection failed:', error) }) ('connect', (e) => { ('Successfully connected to server 111') //Subscribe to a topic ('phone_' + phone, { qos: 0 }, function (err) { if (!err) { //('123', 'Hello mqtt') ("Subscribe successfully") } }) }) // Listen to the return of mq ('message', function (topic, message, packet) { // message is Buffer ("packet", ()) () }) }
Here is an important way to write connection addresses
//('wx://xxxxxxxxxx', options); //wx:// //Protocol version link address//This version of WeChat applet The author himself encapsulated a layer of wx that represents ordinary ws protocol connection wxs that represents wss protocol connection after encryption.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.