Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use mqtt server to realize instant communication in vue

Shulou Source: shulou.com Published: 2022-06-01 03:54:05 09月29日 Update

Today, the editor will share with you how to use the mqtt server to achieve instant messaging in vue. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

MQTT protocol

MQTT (Message Queuing Telemetry Transport, message queuing Telemetry Transmission) is an instant messaging protocol developed by IBM, which may become an important part of the Internet of things. The protocol supports all platforms, connects almost all connected objects to the outside, and is used as a communication protocol for sensors and brakes, such as connecting houses through Twitter.

MQTT is a lightweight broker-based publish / subscribe messaging protocol that connects to remote devices with very little code and bandwidth. For example, through satellite and proxy connections, through dial-up connections with health care providers, and on some automated or small devices, and because of its compact, power-saving, low protocol overhead and efficient transmission of information to one or more receivers, so it is also suitable for mobile application devices.

Vue uses mqtt server to realize instant communication

In most projects, the front-end interaction is just the front-end request back-end interface, which is processed after getting the data. Some time ago, a project in my hand needed to use mqtt. After using it, I thought it was amazing. You only need to subscribe to get the data in real time. Needless to say, sister will give you a step!

1. Install mqtt.js in the vue project

Npm install mqtt-save

two。 Refer to it in the main.js of the project or on the vue page that you need to use

Import mqtt from "mqtt"

3. Define a client object in the data of the vue page for later use

Client: {}

Ok, next is the key point. First, we have to connect to mqtt. The method of 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 is no error. 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 connect 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 called "hello,this is a nice day!" to the topic called "pubtop". Message this.publish ("pubtop", "hello,this is a nice day!")} else {console.log ("message subscription failed!") }});}); / / reconnect this.reconnect () / / whether you have disconnected this.mqttError () / / listen for information this.getMessage ()}

5. Method of publishing messages

/ / publish message @ topic topic @ 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 ("theme is" + topic+ "released successfully")}})}

6. Monitor and receive information about the three topics subscribed above

/ / listen to receive message getMessage () {this.client.on ("message", (topic, message) = > {if (message) {console.log ("received", topic, "message", 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. Listen to whether the server connection failed

/ / listen to whether the server connection failed mqttError () {this.client.on ("error", (error) = > {console.log ("connection failure:", 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 ("Server is disconnected!") }

10. Listen for server reconnection

/ / the listening server reconnects to reconnect () {this.client.on ("reconnect", (error) = > {console.log ("reconnecting:", error)});}, these are all the contents of the article "how to use the mqtt server to achieve instant messaging in vue". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Tags: Subscriptions services servers messages monitoring success communications topics information content knowledge articles projects methods devices and then three most of which are data Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Huawei MariaDB Shulou Tech Info Microsoft