uniapp使用MQTT协议连接emqx

由于项目需求需要在项目中使用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..net/download/FourLeafCloverLLLS/66544387

经验分享 程序员 微信小程序 职场和发展