How to use mqtt in uniapp project

How to use mqtt in uniapp project

Since we need to get some real-time data and display it on the mobile app, we thought of using mqtt for instant messaging.

The following is the whole process of introducing mqtt in uniapp:

1. Reference plugins in the uniapp plugin market

https://ext.dcloud.net.cn/plugin?id=854

2. Specific introduction process

1. Install mqtt and uuid

Run the command lines to install mqtt and uuid respectively in the root directory of the uniapp project. Because uuid will be used to generate the clientId of mqtt later, they are installed together here.

npm install [email protected]

npm install uuid 

Ps.

①The mqtt version installed by me here is the same as the plug-in provided by uniapp. I also tried to install the latest version, and it will report an error, emmmmm...........

②If there is no pakage.json, the installation will prompt an error, but it will not affect the installation and use. If you want to be more convenient, you can add a pakage.json file to the project root directory and add the following content to it:

{
  "name": "",
  "version": "1.0.0",
  "description": "",
  "author": "",
  "license": "MIT",
  "dependencies": {
    "mqtt": "^3.0.0",
    "uuid": "^8.3.0"
  },
  "devDependencies": {},
  "scripts": {}
}

2. The page introduces mqtt and calls

①mqtt connection configuration, placed in /utils/mqtt.js, globally available.

export const MQTT_IP = '192.168.9.128:8083/mqtt' //mqtt address port const MQTT_USERNAME = 'public' //mqtt username const MQTT_PASSWORD = 'public' //password export const MQTT_OPTIONS = {
    connectTimeout: 5000,
    clientId: '',
    username: MQTT_USERNAME,
    password: MQTT_PASSWORD,
    clean: false
}

②vue page references mqtt

The clientId in mqtt uses uuid to generate a unique identification code to prevent data from sticking when different pages subscribe to different topics.

<script>
    import { v4 } from 'uuid';
    import {
        MQTT_IP,
        MQTT_OPTIONS
    } from '@/utils/mqtt.js';
    var mqtt = require('mqtt/dist/mqtt.js')
    var client
    export default {
        data() {
            return {
                topic: '' // Topic to subscribe to}
        },
        mounted() {this.connect() //connect},
        methods: {
            connect() {
                MQTT_OPTIONS.clientId = v4()
                var that = this
                // #ifdef H5
                client = mqtt.connect('ws://' + MQTT_IP, MQTT_OPTIONS)
                // #endif
                // #ifdef MP-WEIXIN||APP-PLUS
                client = mqtt.connect('wx://' + MQTT_IP, MQTT_OPTIONS)
                // #endif
                client.on('connect', function() {
                    console.log('Connection successful')
                    client.subscribe(that.topic, function(err) {
                        if (!err) {
                            console.log('Subscription successful')
                        }
                    })
                }).on('reconnect', function(error) {
                    console.log('Reconnecting...', that.topic)
                }).on('error', function(error) {
                    console.log('Connection failed...', error)
                }).on('end', function() {
                    console.log('Connection disconnected')
                }).on('message', function(topic, message) {
                    console.log('Receive push information:', message.toString())
                })
            }
        }
    }
</script>

3. Operation results

Data changes in real time.

The above is the sharing of methods of using MQTT in uniapp.

The above is the details of how to use MQTT in the uniapp project. For more information about uniapp's use of MQTT, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • uniapp dynamic modification of element node style detailed explanation
  • Detailed explanation of uniapp painless token refresh method
  • Uniapp's experience in developing small programs
  • Ideas and codes for implementing waterfall flow layout in uniapp applet
  • Uniapp WeChat applet: Solution to key failure
  • uniapp realizes the recording upload function

<<:  How to deploy redis in linux environment and install it in docker

>>:  Solution to MySQL error code 1862 your password has expired

Recommend

Detailed explanation of InnoDB storage files in MySQL

Physically speaking, an InnoDB table consists of ...

How to reset MySQL root password

Table of contents 1. Forgot the root password and...

Detailed explanation of common MySQL operation commands in Linux terminal

Serve: # chkconfig --list List all system service...

js precise calculation

var numA = 0.1; var numB = 0.2; alert( numA + num...

A brief discussion on the correct posture of Tomcat memory configuration

1. Background Although I have read many blogs or ...

CSS position fixed left and right double positioning implementation code

CSS Position The position attribute specifies the...

JavaScript canvas to achieve raindrop effect

This article example shares the specific code for...

js native waterfall flow plug-in production

This article shares the specific code of the js n...

Summary on Positioning in CSS

There are four types of positioning in CSS, which...

Detailed usage of kubernetes object Volume

Overview Volume is the abstraction and virtualiza...

Mysql Sql statement comments

You can add comments to MySQL SQL statements. Her...