Skip to content

Commit

Permalink
feat(Websocket): 支持了一个Websocket服务类
Browse files Browse the repository at this point in the history
  • Loading branch information
HammCn committed Aug 17, 2023
1 parent ad53168 commit 6f36b2d
Showing 1 changed file with 48 additions and 4 deletions.
52 changes: 48 additions & 4 deletions websocket/AirWebSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,30 @@ import { AirConfig } from '../config/AirConfig'
import { AirAlert } from '../feedback/AirAlert'

export class AirWebsocket {
/**
* # WebSocket实例
*/
websocket!: WebSocket

/**
* # 是否已连接
*/
isConnected = false

heartBeatTimer!: number
/**
* # 同步Timer
*/
private heartBeatTimer!: number

/**
* # 心跳秒
*/
private heartBeatSecond = 30

heartBeatSecond = 5
/**
* # 自动重连
*/
private reconnectWhenClosed = true

/**
* # 设置Websocket心跳秒
Expand All @@ -32,11 +49,22 @@ export class AirWebsocket {
}
}

/**
* # 是否自动重连
* @param autoConnectWhenClose 是否自动重连
*/
private autoConnectWhenClosed(autoConnectWhenClose = true) {
this.reconnectWhenClosed = autoConnectWhenClose
}

/**
* # 创建一个WebSocket
* @param url [可选]URL
*/
static create(): AirWebsocket {
static create(handler: {
// eslint-disable-next-line no-unused-vars
onmessage?: (message: string) => void,
onopen?: () => void
}): AirWebsocket {
if (!AirConfig.websocketUrl) {
AirAlert.error('请配置环境变量 VITE_APP_WEBSOCKET_URL')
return new AirWebsocket()
Expand All @@ -46,10 +74,26 @@ export class AirWebsocket {
instance.websocket.onopen = () => {
instance.isConnected = true
instance.startHeartBeat()
if (handler.onopen) {
handler.onopen()
}
}
instance.websocket.onmessage = (message) => {
if (handler.onmessage) {
handler.onmessage(message.data)
}
}
instance.websocket.onclose = () => {
instance.isConnected = false
}
return instance
}

/**
* # 关闭WebSocket
*/
close() {
this.reconnectWhenClosed = false
this.websocket.close()
}
}

0 comments on commit 6f36b2d

Please sign in to comment.