From 370469de36c78bb4e26634f84e4392b8832870a3 Mon Sep 17 00:00:00 2001 From: Sebastian Mark Date: Wed, 20 Nov 2024 14:07:00 +0100 Subject: [PATCH] fix: remove client from active connections after write deadline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - add a constant for timeout duration in seconds - set write deadline for client connections - remove client from active connections on error - log additional information when broadcasting fails 🤖 --- internal/websocket/broadcast.go | 9 +++++++-- internal/websocket/client_commands.go | 1 + 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/internal/websocket/broadcast.go b/internal/websocket/broadcast.go index def8309..ac03005 100644 --- a/internal/websocket/broadcast.go +++ b/internal/websocket/broadcast.go @@ -9,6 +9,8 @@ import ( "git.smsvc.net/pomodoro/GoTomato/internal/shared" ) +const TIMEOUT = 10 + // Sends continous messages to all connected WebSocket clients func SendPermanentBroadCastMessage() { tick := time.NewTicker(time.Second) @@ -19,12 +21,15 @@ func SendPermanentBroadCastMessage() { helper.Logger.Error("Error marshalling message:", "msg", err) return } + // Iterate over all connected clients and broadcast the message for _, client := range Clients { + client.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second)) err := client.SendMessage(websocket.TextMessage, jsonMessage) if err != nil { - helper.Logger.Error("Error broadcasting to client:", "msg", err) - // The client is responsible for closing itself on error + // Remove client on error + delete(Clients, client.Conn.LocalAddr()) + helper.Logger.Info("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients)) } } <-tick.C diff --git a/internal/websocket/client_commands.go b/internal/websocket/client_commands.go index 7149faa..6f85108 100644 --- a/internal/websocket/client_commands.go +++ b/internal/websocket/client_commands.go @@ -21,6 +21,7 @@ func handleClientCommands(c models.WebsocketClient) { _, message, err := ws.ReadMessage() if err != nil { + // remove client on error/disconnect delete(Clients, ws.LocalAddr()) helper.Logger.Info("Client disconnected:", "msg", err, "host", c.RealIP, "clients", len(Clients)) break