From 6f36b2d59cc3191cc340b47c05279998c59c2d12 Mon Sep 17 00:00:00 2001 From: Hamm Date: Thu, 17 Aug 2023 10:52:35 +0800 Subject: [PATCH] =?UTF-8?q?feat(Websocket):=20=E6=94=AF=E6=8C=81=E4=BA=86?= =?UTF-8?q?=E4=B8=80=E4=B8=AAWebsocket=E6=9C=8D=E5=8A=A1=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- websocket/AirWebSocket.ts | 52 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 48 insertions(+), 4 deletions(-) diff --git a/websocket/AirWebSocket.ts b/websocket/AirWebSocket.ts index f39c328..84df5e1 100644 --- a/websocket/AirWebSocket.ts +++ b/websocket/AirWebSocket.ts @@ -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心跳秒 @@ -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() @@ -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() + } }