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

Summary of common commands for Linux user and group management

This article summarizes the common commands for L...

ftp remotely connect to Linux via SSH

First install ssh in Linux, taking centos as an e...

Vue example code using transition component animation effect

Transition document address defines a background ...

MySQL optimization: use join instead of subquery

Use JOIN instead of sub-queries MySQL supports SQ...

Detailed explanation of the application of the four states of hyperconnection

Although you think it may be a browser problem, i...

Sharing the structure and expression principles of simple web page layout

Introduction to structure and performance HTML st...

How to compare two database table structures in mysql

During the development and debugging process, it ...

MySQL's conceptual understanding of various locks

Optimistic Locking Optimistic locking is mostly i...

How to clear mysql registry

Specific method: 1. Press [ win+r ] to open the r...

A method of making carousel images with CSS3

Slideshows are often seen on web pages. They have...

CSS overflow-wrap new property value anywhere usage

1. First, understand the overflow-wrap attribute ...

An Uncommon Error and Solution for SQL Server Full Backup

1. Error details Once when manually performing a ...

Do you know the meaning of special symbols in URL?

1.# # represents a location in a web page. The ch...

Introduction to the use of http-equiv attribute in meta tag

meta is an auxiliary tag in the head area of ​​htm...