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

打印 上一主题 下一主题

主题 900|帖子 900|积分 2700

什么?打包空白?分享一下我的办理方法!
第一步
找大师算过了,装4.1版本运气好!
所以根目录执行命令…
  1. npm install mqtt@4.1.0
复制代码
第二步
自己封装一个mqtt文件方便后期开坛做法!
  1. // utils/mqtt.js
  2. import mqtt from 'mqtt/dist/mqtt'
  3. class MQTTClient {
  4.   constructor() {
  5.     this.client = null
  6.     this.subscriptions = new Map()
  7.     this.reconnectTimer = null
  8.     this.config = {
  9.       host: 'mqtt://your-broker.com',
  10.       options: {
  11.         clientId: 'uni-app-' + Date.now(),
  12.         keepalive: 60,
  13.         clean: true,
  14.         reconnectPeriod: 5000
  15.       }
  16.     }
  17.   }
  18.   init() {
  19.     if (!this.client) {
  20.       this.connect()
  21.     }
  22.   }
  23.   connect() {
  24.     this.client = mqtt.connect(this.config.host, this.config.options)
  25.     this.client.on('connect', () => {
  26.       console.log('MQTT Connected')
  27.       this.resubscribe()
  28.     })
  29.     this.client.on('message', (topic, message) => {
  30.       this.handleMessage(topic, message)
  31.     })
  32.     this.client.on('error', (err) => {
  33.       console.error('MQTT Error:', err)
  34.     })
  35.     this.client.on('close', () => {
  36.       console.log('MQTT Connection closed')
  37.       this.scheduleReconnect()
  38.     })
  39.   }
  40.   subscribe(topic, callback) {
  41.     if (!this.subscriptions.has(topic)) {
  42.       this.subscriptions.set(topic, new Set())
  43.       if (this.client?.connected) {
  44.         this.client.subscribe(topic)
  45.       }
  46.     }
  47.     this.subscriptions.get(topic).add(callback)
  48.   }
  49.   unsubscribe(topic, callback) {
  50.     if (this.subscriptions.has(topic)) {
  51.       const callbacks = this.subscriptions.get(topic)
  52.       callbacks.delete(callback)
  53.       if (callbacks.size === 0) {
  54.         this.subscriptions.delete(topic)
  55.         if (this.client?.connected) {
  56.           this.client.unsubscribe(topic)
  57.         }
  58.       }
  59.     }
  60.   }
  61.   handleMessage(topic, message) {
  62.     if (this.subscriptions.has(topic)) {
  63.       const callbacks = this.subscriptions.get(topic)
  64.       callbacks.forEach(cb => cb(message.toString()))
  65.     }
  66.   }
  67.   resubscribe() {
  68.     if (this.client?.connected) {
  69.       const topics = Array.from(this.subscriptions.keys())
  70.       if (topics.length > 0) {
  71.         this.client.subscribe(topics)
  72.       }
  73.     }
  74.   }
  75.   scheduleReconnect() {
  76.     if (!this.reconnectTimer) {
  77.       this.reconnectTimer = setTimeout(() => {
  78.         this.reconnectTimer = null
  79.         this.connect()
  80.       }, 5000)
  81.     }
  82.   }
  83.   destroy() {
  84.     if (this.client) {
  85.       this.client.end()
  86.       this.client = null
  87.     }
  88.     this.subscriptions.clear()
  89.     clearTimeout(this.reconnectTimer)
  90.   }
  91. }
  92. export const mqttClient = new MQTTClient()
复制代码
第三步
打开 main.js 文件
思量前后,以为还是全局挂载吧
  1. import mqtt from '@/mqtt/dist/mqtt.js'
  2. app.config.globalProperties.$mqtt = mqtt;
复制代码
第四步
打开这个mqtt.js修改源码,注意,不是你自己创建的mqtt.js,是安装的依靠库文件,路径在根目的node_modules/mqtt/dist里面!!!!!

然后把里面的代码修改,看图,要改2行!!!源码使用的是 wx.connectSocket,修改之后:uni.connectSocket
末了要加上 complete)=>{}, 别问为什么,一问你就输了!!!!

第五步
到这里已经可以使用了,不信你打包一下app试下,自定义基座也是没问题的!
下面是我的使用代码!
  1. <template>
  2.         <view>
  3.                 收到的MQTT内容===>{{msg}}
  4.         </view>
  5. </template>
  6. <script>
  7.         export default {
  8.                 name: "wang-mqtt",
  9.                 data() {
  10.                         return {
  11.                                 msg: '初始化mqtt'
  12.                         }
  13.                 },
  14.                 created() {
  15.                         // 连接配置
  16.                         let myOptions = {
  17.                                 clientId: 'uni-app-' + Date.now(),
  18.                                 keepalive: 60,
  19.                                 clean: true,
  20.                                 reconnectPeriod: 5000
  21.                         }
  22.                         let ip = ''
  23.                         // #ifdef H5
  24.                          ip = 'ws://你的IP:8083/mqtt'
  25.                         // #endif
  26.                         // #ifdef APP-PLUS
  27.                          ip = 'wx://你的IP:8083/mqtt'
  28.                         // #endif
  29.                         // 创建 MQTT 客户端
  30.                         const client = this.$mqtt.connect(ip, myOptions);
  31.                         // 订阅主题
  32.                         client.subscribe('app_xxdg/topic', (err) => {
  33.                                 if (!err) console.log('成功已订阅主题');
  34.                         });
  35.                         // 监听消息
  36.                         client.on('message', (topic, message) => {
  37.                                 this.msg = message.toString()
  38.                                 console.log(`收到消息:`, message.toString());
  39.                         });
  40.                 },
  41.                 methods: {
  42.                 }
  43.         }
  44. </script>
  45. <style>
  46. </style>
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

数据人与超自然意识

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表