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

Native js realizes the drag and drop of the nine-square grid

Use native JS to write a nine-square grid to achi...

How to add a column to a large MySQL table

The question is referenced from: https://www.zhih...

JS 4 super practical tips to improve development efficiency

Table of contents 1. Short circuit judgment 2. Op...

Three Discussions on Iframe Adaptive Height Code

When building a B/S system interface, you often en...

How to build DockerHub yourself

The Docker Hub we used earlier is provided by Doc...

Three ways to communicate between Docker containers

We all know that Docker containers are isolated f...

Practice of using SuperMap in Vue

Table of contents Preface Related Materials Vue p...

Understanding v-bind in vue

Table of contents 1. Analysis of key source code ...

A brief discussion on the efficiency of MySQL subquery union and in

Recent product testing found a problem that when ...

JavaScript to achieve a simple page countdown

This article example shares the specific code of ...