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-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article Xiaobian for you to introduce in detail "how to use mqtt server to achieve instant messaging in vue", the content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to use mqtt server to achieve instant messaging in vue" can help you solve your doubts.

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 post to the topic called "pubtop" as "hello,this is a nice daylight" Message this.publish ("pubtop", 'hello,this is a nice daylight')} 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 it', message from topic,'', 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+' unsubscribed successfully', error)})}

9. Disconnect

/ / disconnect unconnect () {this.client.end () this.client = null console.log ('server disconnected!') }

10. Listen for server reconnection

/ / the listening server reconnects to reconnect () {this.client.on ('reconnect', (error) = > {console.log (' reconnecting:', error)}) }, reading here, this article "how to use mqtt server to achieve instant messaging in vue" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, please follow 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

Internet Technology

Wechat

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

12
Report