download mqttjs first
yarn add mqtt [email protected]
Why is the 3.0 version? The high version of the high version is unstable on the Internet, then use the stable version;
mqtt online test address, comes with a connected MQTT address;
- First of the address of MQTT:
Export const url = '124. **. ***. 67: 8000/mqtt' // mqtt address port
Remember to configure the Broker to open the WS layer, the terminal is TCP, otherwise it is not even unreasonable./MQTT is necessary.
- MQTT configuration items
// Get clientid // h5 cannot be obtained. I am only used for APP
// const clientid = plus.push.getclientinfo (). Clientid;
// Configuration item
export const options = {
connectTimeOut: 5000,
clientid, // unique ID
Username, // account is not necessary to see if you set it, do you set?
password, // passwords are not necessary
Clean: true,
}
-
to use MQTT page reference,
- Introduce relevant files
Import { url, Options, } From '@/utils/mqtt.js'; var mqtt = reques ('mqtt/dist/mqtt.js') // State a global variable var client;
Here it is best to introduce it with Require.
-
Create a method
// Send information sendMessage () { //this.switches theme name. Parameters sent by buffer. It can be a string or a buffer; client.publish (this.switches, buffer, (e) => { console.log (e) }) }, connect () {{) var that = this // H5's connection is 'ws: //' + url. // #ifdef H5 client = mqtt.connect ('ws: //' + url, options) // #Endif // The connection of the app is 'wx: //' + url. //#Ifdef MP-Weixin || App-Plus client = mqtt.connect ('wx: //' + url, options) // #Endif client.on ('Connect', Function () { console.log ('Connection successful') //that.switches This is similar to the subscription theme name and interface address. They are defined. Just take it directly. After the subscription is successful, you can receive this information. client.subscribe (that.switches, functions (err) { if (! ERR) { console.log ('Switches Successful subscription') } }); client.subscribe (that.drive, function (ERR) { if (! ERR) { console.log ('Drive subscriptions successfully') } }); }). ON ('Reconnect', Function (Error) { console.log ('being reunited ...', that.switches) }). On ('error', function (error) { console.log ('Connection failed ...', error) }). ON ('End', Function () { console.log ('Connection disconnection') }). ON ('Message', Function (Topic, Message) { // Uniformly accept information. TOPIC is the subject name of subscribing. }) }
-
Page Morning after mounting, call
MOUNTED () { this.connect () // connection },
At this point, MQTTJS has been completed simple use. I only use this place, so there is no packaging. If you need it, you can pack it.
The skill is not deep, and he needs to continue to work hard. grateful!
(Original articles, if there are similar, it is pure coincidence. If there is any infringement, contact immediately)