uniapp使用MQTT协议连接emqx

本文详细介绍了如何在uniapp项目中集成MQTT协议,包括安装mqtt和uuid库、配置连接参数、实现连接与消息订阅等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于项目需求需要在项目中使用MQTT协议,特意做了以下文章记录过程

一、安装环境

在uniapp项目根目录下分别运行安装mqtt(安装3.0.0版本的,最新版会有点小问题)和uuid的命令行,因为后面会用uuid生成mqtt的clientId,所以这边就一起安装了。

npm install mqtt@3.0.0
npm install uuid

二、具体使用步骤

1. 页面引入mqtt并调用

1.1 mqtt连接配置参数,放在/utils/mqtt.js里面,全局可用。

mqtt.js内容

export const MQTT_IP = '192.168.9.128:8083/mqtt'//mqtt地址端口, 使用emqx时一定要加mqtt
const MQTT_USERNAME = 'public'//mqtt用户名
const MQTT_PASSWORD = 'public'//密码

export const MQTT_OPTIONS = {
    connectTimeout: 5000,
    clientId: '',
    username: MQTT_USERNAME,
    password: MQTT_PASSWORD,
    clean: false
}

1.2 vue页面引用mqtt

mqtt里面的clientId用uuid生成唯一标识码,因为MQTT协议要求clientID不能一致。在要使用mqtt的vue页面加入以下内容:

<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: '' //要订阅的主题
            }
        },
        mounted() {this.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('连接成功')
                    client.subscribe(that.topic, function(err) {
                        if (!err) {
                            console.log('订阅成功')
                        }
                    })
                }).on('reconnect', function(error) {
                    console.log('正在重连...', that.topic)
                }).on('error', function(error) {
                    console.log('连接失败...', error)
                }).on('end', function() {
                    console.log('连接断开')
                }).on('message', function(topic, message) {
                    console.log('接收推送信息:', message.toString())
                })
            }
        }
    }
</script>

然后你就可以愉快的使用了,以下是我上传的demo代码。
demo源码下载:https://download.youkuaiyun.com/download/FourLeafCloverLLLS/66544387

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

零涂

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值