Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use mqtt server to realize instant communication in vue

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report