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

vue 项目中使用 mqtt

1、在html 中用cdn方式引入

 <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>

2、封装代码 mqtt_connect.js

// import * as mqtt from 'mqtt/dist/mqtt.min'
// 不知道为什么 我用引入的方式不成,就在html 用的cdn方式接入了
import { Message } from 'element-ui'
let client = {}
// 连接服务器
/*** params:* @options 参数*/
export function connectFn({ username, password, url, topic, clientId }, callBack) {const options = {username,password,cleanSession: false,keepAlive: 10,clientId: clientId,connectTimeout: 4000}client = mqtt.connect(url, options)client.on('connect', (e) => {Message.success('成功连接服务器')console.log('成功连接服务器:', e)// 订阅主题console.log(topic, 'topictopic')client.subscribe(topic, { qos: 1 }, (err) => {if (!err) {Message.success('订阅成功')console.log('订阅成功')} else {Message.error('消息订阅失败!')console.log('消息订阅失败!')}})})// 重新连接//   reconnect()// 是否已经断开连接mqttError()// 监听获取信息getMessage(callBack)
}
// 发布消息 @topic主题  @message发布内容
export function publish(topic, message) {if (!client.connected) {console.log('客户端未连接')return}client.publish(topic, message, { qos: 1 }, (err) => {if (!err) {console.log('主题为' + topic + '发布成功')}})
}
// 监听接收消息
function getMessage(callBack) {client.on('message', (topic, message) => {if (message) {callBack(topic, message)}})
}
// 监听服务器是否连接失败
function mqttError() {client.on('error', (error) => {console.log('连接失败:', error)client.end()})
}
// 取消订阅
export function unsubscribe(topicList) {client.unsubscribe(topicList, (error) => {console.log('主题为' + topicList + '取消订阅成功', error)})
}
// 断开连接
export function unconnect() {client.end()client = nullMessage.warning('服务器已断开连接!')console.log('服务器已断开连接!')
}
// 监听服务器重新连接
function reconnect() {client.on('reconnect', (error) => {console.log('正在重连:', error)})
}

3.vue页面中使用

<script>
import { connectFn, unsubscribe, unconnect } from '@/utils/mqtt_connect'export default {data() {return {topicList: []}},mounted() {this.topicList.push(`xxxxx`)connectFn({url: 'xxxxx',username: 'xxx',password: 'xxx',topic: `xxxx`,clientId: `xxxx`},this.getMessage)},beforeDestroy() {unsubscribe(this.topicList)unconnect()},methods: {getMessage(topic, message) {if (message) {console.log('收到来着', topic, '的信息', message.toString())const res = JSON.parse(message.toString())switch (topic) {case 'topic/username':this.username = resbreakcase 'topic/class':this.class = resbreakdefault:return}}}}
}
</script>

http://www.lryc.cn/news/246876.html

相关文章:

  • linux shell操作 - 05 进程 与 IO 模型
  • 让SOME/IP运转起来——SOME/IP系统设计(下)之数据库开发
  • Mybatis反射工厂类DefaultReflectorFactory
  • antDesignPro a-table样式二次封装
  • 找免费4K高清图片素材,就上这6个网站
  • 代码随想录算法训练营第35天| 860.柠檬水找零 406.根据身高重建队列 452. 用最少数量的箭引爆气球
  • 成为AI产品经理——TPR、FPR、ROC、AUC
  • java: Internal error in the mapping processor: java.lang.NullPointerException
  • TCP知识点
  • 大语言模型(LLMs)在 Amazon SageMaker 上的动手实践(一)
  • 顶级数据恢复工具—— 最全的15个数据恢复软件榜单
  • 【图像分类】【深度学习】【Pytorch版本】Inception-ResNet模型算法详解
  • Ubuntu 22.03 LTS 安装deepin-terminal 实现 终端 分屏
  • HTTP协议,Web框架回顾
  • el-checkbox 对勾颜色调整
  • 系统管理精要:深度探索 Linux 监控与管理利器
  • vue3之echarts渐变柱状图
  • 有一种浪漫,叫接触Linux
  • 构建 App 的方法
  • laravel实现发送邮件功能
  • 概要设计检查单、需求规格说明检查单
  • 达梦列式存储和clickhouse基准测试
  • 【Web】NewStarCtf Week2 个人复现
  • Python实现Windows服务自启动、禁用、启动、停止、删除
  • 【华为OD题库-043】二维伞的雨滴效应-java
  • 百度手机浏览器关键词排名优化——提升关键词排名 开源百度小程序源码系统 附带完整的搭建教程
  • Git 的基本概念和使用方式。
  • MarkDown学习
  • 案例:某电子产品电商平台借助监控易保障网络正常运行
  • IntelliJ IDEA 中有什么让你相见恨晚的技巧