这一个TS 封装WebSocket 用法:
const wbSocket = new Socket<T, RT>({ url: url })
wbSocket.onmessage((data: RT) => {
const str = JSON.stringify(data)
console.log('server data:', str)
})
封装如下:
import { Message } from 'element-ui'
export type Callback = (e: Event) => void
export type MessageCallback<RT> = (e: RT) => void
interface Ioptions<RT> {
url: string | null
heartTime?: number
heartMsg?: string
isReconnect?: boolean
isRestory?: boolean
reconnectTime?: number
reconnectCount?: number
openCb?: Callback
closeCb?: Callback
messageCb?: MessageCallback<RT>
errorCb?: Callback
}
export class Heart {
heartTimeOut!: number
ServerHeartTimeOut!: number
timeout = 5000
reset(): void {
clearTimeout(this.heartTimeOut)
clearTimeout(this.ServerHeartTimeOut)
}
start(cb: Callback): void {
this.heartTimeOut = setTimeout((e: Event) => {
cb(e)
this.ServerHeartTimeOut = setTimeout((e: Event) => {
cb(e)
this.reset()
this.start(cb)
}, this.timeout)
}, this.timeout)
}
}
export default class Socket<T, RT> extends Heart {
ws!: WebSocket
reconnectTimer = 0
reconnectCount = 10
options: Ioptions<RT> = {
url: null,
heartTime: 5000,
heartMsg: 'ping',
isReconnect: true,
isRestory: false,
reconnectTime: 5000,
reconnectCount: 5,
openCb: (e: Event) => {
console.log('连接成功的默认回调::::', e)
},
closeCb: (e: Event) => {
console.log('关闭的默认回调::::', e)
},
messageCb: (e: RT) => {
console.log('连接成功的默认回调::::', e)
},
errorCb: (e: Event) => {
console.log('错误的默认回调::::', e)
}
}
constructor(ops: Ioptions<RT>) {
super()
Object.assign(this.options, ops)
this.create()
}
create(): void {
if (!('WebSocket' in window)) {
throw new Error('当前浏览器不支持,无法使用')
}
if (!this.options.url) {
throw new Error('地址不存在,无法建立通道')
}
this.ws = new WebSocket(this.options.url)
this.onopen(this.options.openCb as Callback)
this.onclose(this.options.closeCb as Callback)
this.onmessage(this.options.messageCb as MessageCallback<RT>)
}
onopen(callback: Callback): void {
this.ws.onopen = event => {
clearTimeout(this.reconnectTimer)
this.options.reconnectCount = this.reconnectCount
super.reset()
super.start(() => {
this.send(this.options.heartMsg as string)
})
if (typeof callback === 'function') {
callback(event)
} else {
typeof this.options.openCb === 'function' && this.options.openCb(event)
}
}
}
onclose(callback: Callback): void {
this.ws.onclose = event => {
super.reset()
!this.options.isRestory && this.onreconnect()
if (typeof callback === 'function') {
callback(event)
} else {
typeof this.options.closeCb === 'function' && this.options.closeCb(event)
}
}
}
onerror(callback: Callback): void {
this.ws.onerror = event => {
if (typeof callback === 'function') {
callback(event)
} else {
typeof this.options.errorCb === 'function' && this.options.errorCb(event)
}
}
}
onmessage(callback: MessageCallback<RT>): void {
this.ws.onmessage = (event: MessageEvent<string>) => {
const strMessage = event.data
const { code, data, msg }: KWResponse.Result<RT> = JSON.parse(strMessage)
if (code === 200) {
super.reset()
super.start(() => {
this.send(this.options.heartMsg as string)
})
console.log(data, 'onmessage')
if (typeof callback === 'function') {
callback(data)
} else {
typeof this.options.messageCb === 'function' && this.options.messageCb(data)
}
} else {
Message.error(msg || '收到失败的数据!')
}
}
}
send(data: T | string): void {
if (this.ws.readyState !== this.ws.OPEN) {
throw new Error('没有连接到服务器,无法推送')
}
data = JSON.stringify(data)
this.ws.send(data)
}
onreconnect(): void {
if ((this.options.reconnectCount as number) > 0 || this.options.reconnectCount === -1) {
this.reconnectTimer = setTimeout(() => {
this.create()
if (this.options.reconnectCount !== -1) (this.options.reconnectCount as number)--
}, this.options.reconnectTime)
} else {
clearTimeout(this.reconnectTimer)
this.options.reconnectCount = this.reconnectCount
}
}
destroy(): void {
super.reset()
clearTimeout(this.reconnectTimer)
this.options.isRestory = true
this.ws.close()
}
}
参考文章地址:https://gitcode.net/alnorthword/socket-heart?from_codechina=yes 最后感谢 禅思院的socket-heart
|