ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

ts + websocket封装

ts + websocket封装

1,使用方式

// 开始链接websocket
const ws = websocket({url: '/websocket',onmessage: e => {// 获取websocket信息console.log(e)}
})// 关闭websocket
ws.close()

2,源码如下

// 定义定时器
type TimeoutHandle = ReturnType<typeof setTimeout>// 定义回调函数
interface Fn<T = any, R = T> {(...arg: T[]): R
}// 定义参数
interface IOptions {// 链接url: string// tokentoken?: string// 发送心跳间隔时间heart_time?: number//检查链接状态时间check_time?: number//断线后重连间隔时间lock_time?: number// 成功回调onmessage: Fn<any, any>// 失败回调onerror?: Fn<any, any>// 打开回调onopen?: Fn<any, any>// 关闭回调onclose?: Fn<any, any>
}// 方法
const websocket = (options: IOptions) => {class Ws {// socket实例public ws: WebSocket | undefined// 默认基础地址private readonly baseUrl: string = import.meta.env.VITE_WS_BASE_API as string// socket 地址private readonly url: string | undefined// socket请求成功数据返回回调函数private readonly onmessage: Fn<any, any>// socket请求失败返回回调函数private readonly onerror?: Fn<any, any>// socket打开回调private readonly onopen?: Fn<any, any>// socket关闭回调private readonly onclose?: Fn<any, any>// tokenprivate readonly token: string | undefined = tokenCookies.get()// 心跳时间private readonly heart_time: number = 3000// 检查连接状态时间private readonly check_time: number = 3000// 重连时间private readonly lock_time: number = 4000// 心跳定时器private h_timer: TimeoutHandle | undefined// 检查连接状态定时器private c_timer: TimeoutHandle | undefined// 重连定时器private l_timer: TimeoutHandle | undefined// 重连锁private isLock: boolean = falseconstructor(options: IOptions) {const { url, token, heart_time, check_time, lock_time } = optionsconst { onmessage, onerror, onopen, onclose } = optionsif (!url || !onmessage) {const message = !url ? '链接url' : '回调函数onmessage'throw new Error(`socket${message}不能为空`)}// 链接urlthis.url = this.baseUrl + url// 数据返回回调函数this.onmessage = onmessage// 失败回调if (!!onerror) {this.onerror = onerror}// 打开回调if (!!onopen) {this.onopen = onopen}// 关闭回调if (!!onclose) {this.onclose = onclose}// tokenthis.token = token || tokenCookies.get()// 心跳时间this.heart_time = heart_time || 3000// 检查连接状态时间this.check_time = check_time || 3000// 重连时间this.lock_time = lock_time || 4000// 初始化this.wsInit()}// 初始化socketpublic wsInit(): void {if (!this.url || !this.token) {return}// 拼接tokenconst url = this.url + '?token=' + this.tokenconst ws = new WebSocket(url)// 打开处理ws.onopen = e => {// 心跳this.heartCheck()// 打开回调if (!!this.onopen) {this.onopen(e)}}// 关闭处理ws.onclose = e => {// 重连if (!!this.token) {this.reconnect()}// 关闭回调if (!!this.onclose) {this.onclose(e)}}// 错误处理ws.onerror = e => {// 重连if (!!this.token) {this.reconnect()}// 回调if (!!this.onerror) {this.onerror(e)}}// 消息接收ws.onmessage = e => {// 心跳this.heartCheck()// 回调this.onmessage(e)}// 赋值this.ws = ws}// 心跳private heartCheck(): void {// 清除心跳、检查连接接定时器this.clearTimeout()// 心跳定时器this.h_timer = setTimeout(() => {// 发送ping;(this.ws as WebSocket).send('type:ping')// 检查连接状态定时器,确认连接状态this.c_timer = setTimeout(() => {// 连接失败,进行关闭if ((this.ws as WebSocket).readyState !== 1) {this.close()}}, this.check_time)}, this.heart_time)}// 重连private reconnect(): void {if (this.isLock) {return}this.isLock = truethis.l_timer && clearTimeout(this.l_timer)// 重连定时器this.l_timer = setTimeout(() => {this.wsInit()this.isLock = false}, this.lock_time)}// 清除心跳、检查连接状态定时器private clearTimeout(): void {this.h_timer && clearTimeout(this.h_timer)this.c_timer && clearTimeout(this.c_timer)}// 销毁关闭public close(): void {// 关闭WebSocket;(this.ws as WebSocket).close()// 清除心跳、检查连接接定时器this.clearTimeout()}}return new Ws(options)
}
export default websocket
返回列表