From ef699a912348bd75c3b5025a1a8020b73e139ff4 Mon Sep 17 00:00:00 2001 From: Tilman Vatteroth Date: Sun, 26 Mar 2023 15:16:18 +0200 Subject: [PATCH] fix: disconnect websocket if trying to send over closed connection Signed-off-by: Tilman Vatteroth --- .../websocket-transporter.ts | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/commons/src/message-transporters/websocket-transporter.ts b/commons/src/message-transporters/websocket-transporter.ts index f3e32a44f..bf1e629d2 100644 --- a/commons/src/message-transporters/websocket-transporter.ts +++ b/commons/src/message-transporters/websocket-transporter.ts @@ -28,7 +28,7 @@ export class WebsocketTransporter extends MessageTransporter { this.websocket = websocket this.bindWebsocketEvents(websocket) - if (this.websocket.readyState === WebSocket.OPEN) { + if (this.isConnected()) { this.onConnected() } else { this.websocket.addEventListener('open', this.onConnected.bind(this)) @@ -69,13 +69,26 @@ export class WebsocketTransporter extends MessageTransporter { } protected onDisconnecting() { + if (this.websocket === undefined) { + return + } this.undbindEventsFromPreviousWebsocket() + this.websocket = undefined super.onDisconnecting() } public sendMessage(content: Message): void { - if (this.websocket?.readyState !== WebSocket.OPEN) { - throw new Error("Can't send message over non-open socket") + if (!this.isConnected()) { + this.onDisconnecting() + console.debug( + "Can't send message over closed connection. Triggering onDisconencted event. Message that couldn't be sent was", + content + ) + return + } + + if (this.websocket === undefined) { + throw new Error('websocket transporter has no websocket connection') } try {