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 ...
随机推荐
- Spring Event 观察者模式, 业务解耦神器
观察者模式在实际开发过程中是非常常见的一种设计模式. Spring Event的原理就是观察者模式,只不过有Spring的加持,让我们更加方便的使用这一设计模式. 一.什么是观察者模式 概念: 观察者 ...
- WPF动画入门教程
Windows Presentation Foundation (WPF)是一种用于创建Windows客户端应用程序的UI框架.它让我们能够创建丰富的图形界面,包括各种各样的动画效果.接下来,我们将介 ...
- python基础:集合(set)字典(direction)介绍
三.字典(dict) 1.字典的创建赋值创建字典In [2]: d = {1,True,"hello"} In [3]: type(d)Out[3]: set #字典由key和va ...
- Node学习第一步 | 简介及安装
什么是node Javascript可以在浏览器运行, node可以让javascript在浏览器之外运行 可以用来做本地运行的软件/网络服务器/游戏等等 记得安装vs code里面力扣插件需要先安装 ...
- mysql8安装踩坑记
背景:已安装mysql5.7版本 问题一:默认的3306端口被占用 进入mysql5.7的my.ini文件,更改port为3307或者其他未被占用的端口 问题二:Install/Remove of t ...
- Mybatis-Plus 系列:简介和基本使用
目录 一.简介 二.特性 三.基本使用 1.初始化数据库 2.初始化工程 3.精简 SpringBoot 相关日志 一.简介 官网:https://www.baomidou.com MyBatis-P ...
- 异常:no transaction is in progress
转载请注明出处: 在使用 @Scheduled 注解创建了一个定时任务,并通过定时任务不断向mysql写入数据,写入数据的方式是通过 jpa 的方式,在代码运行的过程中出现错误:no transac ...
- ORA-10456: cannot open standby database; media recovery session may be in progress
SQL> alter database recover managed standby database disconnect from session;Database altered.SQL ...
- Python--乱码转化为中文
1. \u和\x的含义 \u:代表的是unicode码 \x:代表的是16进制码 2. 代码实现 :\x类型 # \xe4\xb8\xad\xe6\x96\x87 代表的意思是'中文' s = u'\ ...
- 01--OpenStack 手动安装手册(Icehouse)
#OpenStack 手动安装手册(Icehouse) 声明:本博客欢迎转发,但请保留原作者信息!作者:[罗勇] 云计算工程师.敏捷开发实践者博客:http://yongluo2013.github. ...