From 73a8fcd35ba1399be771cd9efafd6cc6a5cbcd6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=89=8B=E7=93=9C=E4=B8=80=E5=8D=81=E9=9B=AA?= Date: Sun, 11 Aug 2024 00:11:51 +0800 Subject: [PATCH] =?UTF-8?q?chore:=20=E5=88=9D=E6=AD=A5=E5=AE=8C=E6=88=90ne?= =?UTF-8?q?twork?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/onebot/network/passive-websocket.ts | 38 +++++++++++++++++++++---- 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/src/onebot/network/passive-websocket.ts b/src/onebot/network/passive-websocket.ts index a7dfb5eb..75c6f9fd 100644 --- a/src/onebot/network/passive-websocket.ts +++ b/src/onebot/network/passive-websocket.ts @@ -29,8 +29,7 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter { } } wsClient.on('message', (message) => { - // TODO: extract action name and payload from the message, then call the corresponding action. - // TODO: consider using a utility function + this.handleMessage(message); }); wsClient.once('close', () => { this.wsClientsMutex.runExclusive(async () => { @@ -51,15 +50,22 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter { } registerHeartBeat() { - //WS正向心跳 + setInterval(() => { + this.wsClientsMutex.runExclusive(async () => { + this.wsClients.forEach((wsClient) => { + if (wsClient.readyState === WebSocket.OPEN) { + wsClient.ping(); + } + }); + }); + }, this.heartbeatInterval); } onEvent(event: T) { this.wsClientsMutex.runExclusive(async () => { this.wsClients.forEach((wsClient) => { - // wsClient.send(JSON.stringify(event)); - // TODO: wrap the event, and send the wrapped to the client. - // TODO: consider using a utility function + const wrappedEvent = this.wrapEvent(event); + wsClient.send(JSON.stringify(wrappedEvent)); }); }); } @@ -76,4 +82,24 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter { this.hasBeenClosed = true; this.wsServer.close(); } + + private handleMessage(message: any) { + try { + const parsedMessage = JSON.parse(message); + const action = this.actionMap.get(parsedMessage.actionName); + if (action) { + action.handle(parsedMessage.payload); + } + } catch (e) { + console.error('Failed to handle message:', e); + } + } + + private wrapEvent(event: T) { + return { + type: 'event', + data: event + }; + } } +