TS MQTT封装
TS MQTT封装
导入相关包
npm i mqtt
npm i lodash
- guid 随机生成就行,具体可以参考百度或者随便生成一个随机数*
代码封装
import mqtt from 'mqtt'
import type { MqttClient, OnMessageCallback, IClientOptions, IClientPublishOptions, IPublishPacket } from 'mqtt'
import { getGuid } from '@/common/basic'
import { without, uniq } from 'lodash'
export type TPublishFormat = {
topic: string
payload: string | Buffer
opts?: IClientPublishOptions
}
export type TMessageCallback<T> = (topic: string, payload: T) => void
export interface IMqClientOptions extends IClientOptions {
connectCb?: () => void
errorCb?: (e: Event) => void
reconnectCb?: () => void
}
export default class MQTT {
private _type: string
private _url: string
private _opt: IMqClientOptions // mqtt地址
public client!: MqttClient
public topicArr: Array<string> = []
constructor(url: string, opt?: IMqClientOptions, type: string = 'Web') {
this._type = type
this._url = url
this._opt = {
clean: true,
clientId: this._type + '_' + getGuid(), // 客户端分类唯一
connectTimeout: 3000, // 超时时间
reconnectPeriod: 1000, //重连超时
...(opt && opt),
}
this._init()
}
private _init() {
this.destroy()
this.client = mqtt.connect(this._url, this._opt)
this.client.on('connect', () => {
this._opt.connectCb && this._opt.connectCb()
console.log(this._url + '连接成功...')
})
this.client.on('error', (error: any) => {
this._opt.errorCb && this._opt.errorCb(error)
console.log(this._url + '异常中断...')
})
this.client.on('reconnect', () => {
this._opt.reconnectCb && this._opt.reconnectCb()
console.log(this._url + '重新连接...')
})
}
/**
* 函数“unSubscribe”是一个 TypeScript 函数,用于取消订阅一个或多个主题,并返回一个 Promise,该 Promise 解析为一个布尔值,指示取消订阅是否成功。
* @param {string | string[]} topic - topic 参数可以是字符串或字符串数组。它代表客户端想要取消订阅的主题。
* @returns 正在返回 Promise。
*/
public unSubscribe(topic: string | string[]) {
return new Promise((resolve: (isOk: boolean) => void) => {
this.client &&
!this.client.disconnected &&
this.client
.unsubscribeAsync(topic)
.then((result) => {
if (typeof topic === 'string') {
topic = [topic]
}
//去重
this.topicArr = without(this.topicArr, ...topic)
console.log(topic, this.topicArr, '取消订阅成功...')
resolve(true)
})
.catch((err) => {
console.log(topic, '取消订阅失败...')
resolve(false)
})
})
}
/**
* 函数“onSubscribe”是一个 TypeScript 函数,它订阅一个或多个主题并返回一个 Promise,该 Promise 解析为一个布尔值,指示订阅是否成功。
* @param {string | string[]} topic - topic 参数可以是字符串或字符串数组。它代表您要订阅的主题。
* @returns 一个 Promise,解析为布尔值,指示订阅是否成功。
*/
public onSubscribe(topic: string | string[]) {
if (typeof topic === 'string') {
topic = [topic]
}
const topicOk: Array<string> = without(topic, ...this.topicArr)
return new Promise((resolve: (isOk: boolean) => void) => {
this.client &&
!this.client.disconnected &&
topicOk.length > 0 &&
this.client
.subscribeAsync(topic)
.then((result) => {
this.topicArr.push(...topicOk)
this.topicArr = uniq(this.topicArr)
console.log(topicOk, this.topicArr, '订阅成功...')
resolve(true)
})
.catch((err) => {
console.log(topicOk, '订阅失败...')
resolve(false)
})
})
}
/**
* 函数“onPublish”使用客户端向主题发布消息,并返回一个解析为布尔值的 Promise,指示发布是否成功。
* @param {TPublishFormat} format - format参数的类型为TPublishFormat,它是一个包含两个属性的对象:topic和message。 topic
* 属性表示消息将发布到的主题,message 属性表示将发布的实际消息。
* @returns 正在返回 Promise。
*/
public onPublish(format: TPublishFormat) {
return new Promise((resolve: (isOk: boolean) => void) => {
this.client &&
!this.client.disconnected &&
this.client
.publishAsync(format.topic, format.payload, format.opts)
.then((result) => {
console.log('发布消息成功...')
resolve(true)
})
.catch((err) => {
console.log('发布消息失败...')
resolve(false)
})
})
}
//收到的消息
public onMessage<T = any>(callback: TMessageCallback<T>) {
this.client &&
!this.client.disconnected &&
this.client.on('message', (topic: string, payload: Buffer) => {
try {
callback && callback(topic, JSON.parse(payload.toString()))
} catch (err) {
console.log('无法执行JSON.parse...')
callback && callback(topic, payload.toString() as T)
}
})
}
//销毁
public destroy() {
console.log('销毁...')
this.client && this.client.end()
this.topicArr = []
}
}
使用
//通过开源公共服务器测试,切换成自家服务器就行了
const mqtt = new MQTT('mqtt://broker.emqx.io:8083/mqtt', { username: 'emqx_test', password: 'emqx_test' })
mqtt.onSubscribe('/test/ss')
mqtt.onMessage((topic, message) => {
console.log(topic, message)
})
setTimeout(() => {
mqtt.onPublish({ topic: '/sss/ss', payload: '测试1111' })
}, 3000);
TS MQTT封装的更多相关文章
- 关于对H264码流的TS的封装的相关代码实现
1 写在开始之前 在前段时间有分享一个H264封装ps流到相关文章的,这次和大家分享下将H264封装成TS流到相关实现,其实也是工作工作需要.依照上篇一样,分段说明每个数据头的封装情况,当然,一样也会 ...
- ESA2GJK1DH1K基础篇: Android实现MQTT封装源码使用说明
说明 这一节说明一下基础篇APP源码里面MyMqttCilent.java这个文件的使用 新建工程 安装MQTT的jar包 implementation 'org.eclipse.paho:org.e ...
- 自己动手写RTP服务器——用RTP协议传输TS流
上一篇文章我们介绍了关于RTP协议的知识,那么我们现在就自己写一个简单的传输TS流媒体的RTP服务器吧. 预备知识 关于TS流的格式:TS流封装的具体格式请参考文档ISO/IEC 13818-1.这里 ...
- 关于TCP和MQTT之间的转换(转载)
现在物联网流行的就是MQTT 其实MQTT就是在TCP的基础上建立了一套协议 可以看这个,本来我自己想用Wireshark监听一下,不过百度一搜索一大把,我就不测试了 https://blog.csd ...
- 关于TCP和MQTT之间的转换
现在物联网流行的就是MQTT 其实MQTT就是在TCP的基础上建立了一套协议 可以看这个,本来我自己想用Wireshark监听一下,不过百度一搜索一大把,我就不测试了 https://blog.csd ...
- FFMPEG中关于ts流的时长估计的实现(转)
最近在做H.265 编码,原本只是做编码器的实现,但客户项目涉及到ts的封装,搞得我不得不配合了解点ts方面的东西.下面技术文档不错,转一下. ts流中的时间估计 我们知道ts流中是没有时间信息的,我 ...
- 基于ElementUI封装Excel数据导入组件
由于前端项目使用的是Vue-cli3.0 + TypeScript的架构,所以该组件也是基于ts语法封装的,组件的完整代码如下: <template> <div id="m ...
- ts流中的pcr与pts计算与逆运算
mpeg2ts文件格式中有pcr和pts的概念,其代码含义如下: PCR(Program Clock Reference)--指示系统时钟本身的瞬时值的时间标签称为节目参考时钟标签(PCR). PTS ...
- Angular:使用service进行http请求的简单封装
①使用ng g service services/storage创建一个服务组件 ②在app.module.ts 中引入HttpClientModule模块 ③在app.module.ts 中引入创建 ...
- 一些好用的javascript/typescript方法封装分享
1.数字格式化 JS版-直接写到原型链上 /** * @author: silencetea * @name: * @description: 数字格式化,默认每三位用英文逗号分隔 * @param ...
随机推荐
- 分享一个 SpringBoot + Redis 实现「查找附近的人」的小技巧
前言 SpringDataRedis提供了十分简单的地理位置定位的功能,今天我就用一小段代码告诉大家如何实现. 正文 1.引入依赖 <dependency> <groupId> ...
- FastGPT 接入飞书(不用写一行代码)
FastGPT V4 版本已经发布,可以通过 Flow 可视化进行工作流编排,从而实现复杂的问答场景,例如联网谷歌搜索,操作数据库等等,功能非常强大,还没用过的同学赶紧去试试吧. 飞书相比同类产品算是 ...
- Solution -「CSP 2019」Partition
Description Link. 给出一个数列,要求将其分成几段,使每段的和非严格递增,求最小的每段的和的平方和. Solution 注意到 \(a_{i}\) 为正,对于正数有这样的结论: \[a ...
- Spring Boot 目录遍历--表达式注入--代码执行--(CVE-2021-21234)&&(CVE-2022-22963)&&(CVE-2022-22947)&&(CVE-2022-2296)
Spring Boot 目录遍历--表达式注入--代码执行--(CVE-2021-21234)&&(CVE-2022-22963)&&(CVE-2022-22947)& ...
- SpringBoot项目优雅停机+Pid暴力停机
bootstrap.yaml配置项目的pid输出位置 spring: pid: file: F:/cloud-nacos/cloud_gateway/application.pid springboo ...
- NFC and Contactless Technologies
NFC and Contactless Technologies NFC与无接触技术 NFC technology enables simple and safe two-way interactio ...
- Java21上手体验-分代ZGC和虚拟线程
一.导语 几天前Oracle刚刚发布了Java21, 由于这是最新的LTS版本,引起了大家的关注. 我也第一时间在个人项目中进行了升级体验. 一探究竟,和大家分享. 二.Java21更新内容介绍 官方 ...
- 再学Blazor——组件
Blazor 应用基于组件,组件可以复用和嵌套.本文内容如下: 组件类 组件嵌套 组件参数 组件对象 1. 组件类 所有组件都是继承 ComponentBase 组件基类,razor 文件默认继承 C ...
- 命令vue inspect > output.js报错:在此系统上禁止运行脚本
用的这个命令去看output.js文件,结果报错. 解决方案是去对应目录下删掉vue.ps1就OK了 .
- 推荐一款“自学编程”的宝藏网站!详解版~(在线编程练习,项目实战,免费Gpt等)
云端源想学习平台,一站式编程服务网站云端源想官网传送门 精品课程:由项目实战为导向的视频课程,知识点讲解配套编程练习,让初学者有方向有目标. 课程阶段:每门课程都分多个阶段进行,由浅入深,很适合零基础 ...