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

news/2025/2/25 16:13:07

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

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

javascript">npm install mqtt@4.1.0

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

javascript">// 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 文件
思量前后,觉得还是全局挂载吧

javascript">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试下,自定义基座也是没问题的!
下面是我的使用代码!

javascript"><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>

http://www.niftyadmin.cn/n/5865692.html

相关文章

鸿蒙NEXT开发-位置服务

注意&#xff1a;博主有个鸿蒙专栏&#xff0c;里面从上到下有关于鸿蒙next的教学文档&#xff0c;大家感兴趣可以学习下 如果大家觉得博主文章写的好的话&#xff0c;可以点下关注&#xff0c;博主会一直更新鸿蒙next相关知识 目录 1. 位置服务基本介绍 2. 申请位置权限 …

比较Spring AOP和AspectJ

1. 介绍 当前有多个可用的AOP库&#xff0c;这些库必须能够回答许多问题&#xff1a; 它与我现有的或新的应用程序兼容吗&#xff1f;在哪里可以实施AOP&#xff1f;它与我的应用程序集成的速度有多快&#xff1f;性能开销是多少&#xff1f; 在本文中&#xff0c;我们将着眼…

世优科技国内首家 MR 体验店开业,打造 MAS 任意门奇幻之旅

在科技飞速发展的当下,元宇宙与现实世界的融合正逐渐从概念走向现实。 近日,世优科技打造的 MAS 任意门创新体验馆,在常州环球港商圈首发开业,这一里程碑事件不仅标志着世优科技在 MR 领域的深度布局,更开启了大众体验前沿科技的全新篇章。 常州 MAS 体验馆的开业,吸引了众多科…

【Python爬虫(64)】从“听”开始:Python音频爬虫与语音数据处理全解析

【Python爬虫】专栏简介&#xff1a;本专栏是 Python 爬虫领域的集大成之作&#xff0c;共 100 章节。从 Python 基础语法、爬虫入门知识讲起&#xff0c;深入探讨反爬虫、多线程、分布式等进阶技术。以大量实例为支撑&#xff0c;覆盖网页、图片、音频等各类数据爬取&#xff…

DirectX12(D3D12)基础教程三 线性代数与3D世界空间

线性代数是数学的一个分支&#xff0c;它的研究对象是向量&#xff0c;向量空间&#xff08;或称线性空间&#xff09;&#xff0c;线性变换和有限维的线性方程组。 向量和矩阵是学习3D入门最基本的理论基础。本章重点讲向量和矩阵. 向量概念 向量最基本的定义就是一个方向和…

vue 3D 翻页效果

<template><view class"swipe-container" touchstart"onTouchStart" touchmove"onTouchMove" touchend"onTouchEnd"><view class"page">初始页</view></view> </template><script&g…

【网络编程】几个常用命令:ping / netstat / xargs / pidof / watch

ping&#xff1a;检测网络联通 1. ping 的基本功能2. ping 的工作原理3. ping 的常见用法4. ping 的输出解释5. ping 的应用场景6. 注意事项 netstat&#xff1a;查看网络状态 1. netstat 的基本功能2. 常见用法3. 示例4. 输出字段解释5. netstat 的替代工具6. 注意事项 xargs&…

Sky Hackathon 清水湾的水 AI美食助手

这里写自定义目录标题 视频 视频 video