当前位置: 首页 > news >正文

uniapp在app下使用mqtt协议!!!支持vue3

什么?打包空白?分享一下我的解决方法!

第一步
找大师算过了,装4.1版本运气好!
所以根目录执行命令…

npm install mqtt@4.1.0

第二步
自己封装一个mqtt文件方便后期开坛做法!

// utils/mqtt.js
import mqtt from 'mqtt/dist/mqtt'

class MQTTClient {
  constructor() {
    this.client = null
    this.subscriptions = new Map()
    this.reconnectTimer = null
    this.config = {
      host: 'mqtt://your-broker.com',
      options: {
        clientId: 'uni-app-' + Date.now(),
        keepalive: 60,
        clean: true,
        reconnectPeriod: 5000
      }
    }
  }

  init() {
    if (!this.client) {
      this.connect()
    }
  }

  connect() {
    this.client = mqtt.connect(this.config.host, this.config.options)

    this.client.on('connect', () => {
      console.log('MQTT Connected')
      this.resubscribe()
    })

    this.client.on('message', (topic, message) => {
      this.handleMessage(topic, message)
    })

    this.client.on('error', (err) => {
      console.error('MQTT Error:', err)
    })

    this.client.on('close', () => {
      console.log('MQTT Connection closed')
      this.scheduleReconnect()
    })
  }

  subscribe(topic, callback) {
    if (!this.subscriptions.has(topic)) {
      this.subscriptions.set(topic, new Set())
      if (this.client?.connected) {
        this.client.subscribe(topic)
      }
    }
    this.subscriptions.get(topic).add(callback)
  }

  unsubscribe(topic, callback) {
    if (this.subscriptions.has(topic)) {
      const callbacks = this.subscriptions.get(topic)
      callbacks.delete(callback)
      if (callbacks.size === 0) {
        this.subscriptions.delete(topic)
        if (this.client?.connected) {
          this.client.unsubscribe(topic)
        }
      }
    }
  }

  handleMessage(topic, message) {
    if (this.subscriptions.has(topic)) {
      const callbacks = this.subscriptions.get(topic)
      callbacks.forEach(cb => cb(message.toString()))
    }
  }

  resubscribe() {
    if (this.client?.connected) {
      const topics = Array.from(this.subscriptions.keys())
      if (topics.length > 0) {
        this.client.subscribe(topics)
      }
    }
  }

  scheduleReconnect() {
    if (!this.reconnectTimer) {
      this.reconnectTimer = setTimeout(() => {
        this.reconnectTimer = null
        this.connect()
      }, 5000)
    }
  }

  destroy() {
    if (this.client) {
      this.client.end()
      this.client = null
    }
    this.subscriptions.clear()
    clearTimeout(this.reconnectTimer)
  }
}

export const mqttClient = new MQTTClient()

第三步
打开 main.js 文件
思量前后,觉得还是全局挂载吧

import mqtt from '@/mqtt/dist/mqtt.js'
app.config.globalProperties.$mqtt = mqtt;

第四步
打开这个mqtt.js修改源码,注意,不是你自己创建的mqtt.js,是安装的依赖库文件,路径在根目的node_modules/mqtt/dist里面!!!!!
在这里插入图片描述
然后把里面的代码修改,看图,要改2行!!!源码使用的是 wx.connectSocket,修改之后:uni.connectSocket
最后要加上 complete:()=>{}, 别问为什么,一问你就输了!!!!
在这里插入图片描述
第五步
到这里已经可以使用了,不信你打包一下app试下,自定义基座也是没问题的!
下面是我的使用代码!

<template>
	<view>
		收到的MQTT内容===>{{msg}}
	</view>
</template>

<script>
	export default {
		name: "wang-mqtt",
		data() {
			return {
				msg: '初始化mqtt'
			}
		},
		created() {
			// 连接配置
			let myOptions = {
				clientId: 'uni-app-' + Date.now(),
				keepalive: 60,
				clean: true,
				reconnectPeriod: 5000
			}
			let ip = ''
			// #ifdef H5
			 ip = 'ws://你的IP:8083/mqtt'
			// #endif
			// #ifdef APP-PLUS
			 ip = 'wx://你的IP:8083/mqtt'
			// #endif

			// 创建 MQTT 客户端
			const client = this.$mqtt.connect(ip, myOptions);
			// 订阅主题
			client.subscribe('app_xxdg/topic', (err) => {
				if (!err) console.log('成功已订阅主题');
			});
			// 监听消息
			client.on('message', (topic, message) => {
				this.msg = message.toString()
				console.log(`收到消息:`, message.toString());
			});
		},
		methods: {

		}
	}
</script>
<style>
</style>

相关文章:

  • DeepSeek技术:数字化时代的商业规则重塑者
  • 19、《Springboot+MongoDB整合:玩转文档型数据库》
  • llama.cpp 一键运行本地大模型 - Windows
  • esp工程报错:something went wrong when trying to build the project esp-idf 一种解决办法
  • [AI相关]问问DeepSeek如何基于Python,moviePy实现视频字幕功能
  • 【量化策略】动量反转策略
  • Docker:Docker从入门到精通(一)- Docker简介
  • 如何实现修改jvm中类的属性开源项目
  • react使用react-quill 富文本插件、加入handlers富文本不显示解决办法
  • vLLM专题(十一)-工具调用(Tool Calling)
  • 详解传输层协议TCP/UDP
  • 力扣hot100——岛屿数量 岛屿问题经典dfs总结
  • 安全面试5
  • 常见高低压开关柜
  • 「软件设计模式」责任链模式(Chain of Responsibility)
  • Python Seaborn库使用指南:从入门到精通
  • RPA自动化测试流程构建体系搭建 实例
  • 分库分表中间件开源
  • matlab ylabel怎么让y轴显示的标签是正的
  • JavaWeb-Servlet对象生命周期
  • 俄媒:俄乌代表团抵达谈判会场
  • 美国务卿会见叙利亚外长,沙特等国表示将支持叙利亚重建
  • 烤肉店从泔水桶内捞出肉串再烤?西安未央区市监局:停业整顿
  • 一图读懂丨创新创业人才最高补贴500万元!临港新片区发布创客新政“十二条”
  • 网易一季度净利增长三成,丁磊:高度重视海外游戏市场
  • 申论|空间更新结合“青银共生”,助力青年发展型城区建设