MQTT ProtocolMQTT (Message Queuing Telemetry Transport) is an instant messaging protocol developed by IBM and has the potential to become an important part of the Internet of Things. The protocol supports all platforms and can connect almost all Internet-connected objects to the outside world. It is used as a communication protocol for sensors and actuators (such as connecting houses to the Internet via Twitter). MQTT is a lightweight broker-based publish/subscribe messaging protocol that can connect to remote devices with minimal code and bandwidth. For example, via satellite and proxy connections, via dial-up and healthcare provider connections, and in some automated or small devices. It is also suitable for mobile application devices due to its small size, power saving, low protocol overhead and ability to efficiently transmit information to one or multiple recipients. Vue uses mqtt server to realize instant communicationIn most projects, the front-end and back-end interaction is just the front-end requesting the back-end interface, and then processing the data after getting it. Some time ago, a project I was working on required the use of mqtt. After using it, I found it magical. I only need to subscribe to get data in real time. Without further ado, I will give you the steps! 1. Install mqtt.js in the vue project npm install mqtt --save 2. Reference it in the main.js of the project or on the vue page where it is needed import mqtt from 'mqtt' 3. Define a client object in the data of the vue page for later use client: {} Ok, the next step is the key point. First, we have to connect to MQTT. The method for connecting to MQTT has a callback function. Next, I will write the subscription method in the callback after the connection is successful, so as to ensure that there will be no errors. Here is the code! 4. Connect to MQTT and subscribe //Connect to the server connect() { let options = { username: "xxx", password: "xxxx", cleanSession : false, keepAlive:60, clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8), connectTimeout: 4000 } this.client = mqtt.connect('ws://192.168.xxx.xx:8083/mqtt',options); this.client.on("connect", (e)=>{ console.log("Successfully connected to the server:",e); //Subscribe to three topics named 'top/#', 'three/#' and '#' this.client.subscribe(['top/#', 'three/#', '#'], { qos: 1 }, (err)=> { if (!err) { console.log("Subscription successful"); //Publish a message with the content 'hello, this is a nice day!' to the topic "pubtop" this.publish("pubtop", 'hello, this is a nice day!') } else { console.log('Message subscription failed!') } }); }); //Reconnect this.reconnect() //Has the connection been disconnected? this.mqttError() //Listen for information this.getMessage() } 5. Publish message method //Publish message @topic subject @message publish content publish(topic,message) { if (!this.client.connected) { console.log('Client not connected') return } this.client.publish(topic,message,{qos: 1},(err) => { if(!err) { console.log('The subject is' + topic + "Published successfully") } }) } 6. Listen and receive information from the three topics subscribed above //Listen for received messages getMessage() { this.client.on("message", (topic, message) => { if(message) { console.log('Received from', topic, 'information', message.toString()) const res = JSON.parse(message.toString()) //console.log(res, 'res') switch(topic) { case 'top/#' : this.msg = res break; case 'three/#' : this.msg = res break; case 'three/#' : this.msg = res break; default: return this.msg = res } this.msg = message } }); }, 7. Check if the server connection fails //Monitor whether the server connection fails mqttError() { this.client.on('error',(error) => { console.log('Connection failed:',error) this.client.end() }) }, 8. Unsubscribe //Unsubscribe unsubscribe() { this.client.unsubscribe(this.mtopic, (error)=> { console.log('Topic is' + this.mtopic + 'Unsubscribe successfully', error) }) }, 9. Disconnect //disconnect unconnect() { this.client.end() this.client = null console.log('The server has been disconnected!') }, 10. Listen for server reconnection //Listen for server reconnection reconnect() { this.client.on('reconnect', (error) => { console.log('Reconnecting:', error) }); }, SummarizeThis is the end of this article about using mqtt server in vue to realize instant messaging. For more relevant content about using mqtt instant messaging in vue, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Detailed tutorial for installing nginx on centos8 (picture and text)
>>: Nginx forward and reverse proxy and load balancing functions configuration code example
Use regular expressions to determine the IE browse...
Preface Use js to achieve a year rotation selecti...
I logged into the backend to check the solution t...
1: Check the PHP version after entering the termi...
Table of contents 1. Preliminary preparation 1.1 ...
Table of contents The basic principle of MySQL ma...
Table of contents 1. The following code is a simp...
This article example shares the specific code of ...
Table of contents Audio transcoding tools princip...
This article mainly introduces the analysis of My...
1. The effect diagram implemented in this article...
The topic I want to share with you today is: &quo...
1. [admin@JD ~]$ cd opt #Enter opt in the root di...
Table of contents 1. We must ensure that the vue/...
How to save and exit after editing a file in Linu...