From 7e5b0659b40f4f7b3b161e47517e8adac1a0d178 Mon Sep 17 00:00:00 2001 From: Sebastian Mark Date: Wed, 20 Nov 2024 21:50:43 +0100 Subject: [PATCH] move stale client check to `RemoveStaleClients()` --- cmd/server/main.go | 1 + internal/websocket/broadcast.go | 5 ----- internal/websocket/staleClients.go | 21 +++++++++++++++++++++ 3 files changed, 22 insertions(+), 5 deletions(-) create mode 100644 internal/websocket/staleClients.go diff --git a/cmd/server/main.go b/cmd/server/main.go index d8eb8f6..78c5c99 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -54,6 +54,7 @@ func Start() { r := http.NewServeMux() r.HandleFunc("/", websocket.HandleConnection) go websocket.SendPermanentBroadCastMessage() + go websocket.RemoveStaleClients() helper.Logger.Info("GoTomato started", "version", metadata.GoTomatoVersion) helper.Logger.Info("Websocket listening", "address", listen) diff --git a/internal/websocket/broadcast.go b/internal/websocket/broadcast.go index aadfab6..f84c499 100644 --- a/internal/websocket/broadcast.go +++ b/internal/websocket/broadcast.go @@ -22,11 +22,6 @@ func SendPermanentBroadCastMessage() { // Iterate over all connected clients and broadcast the message for _, client := range Clients { - // Remove unresponsive client - if client.IsStale() { - client.Conn.Close() - continue - } // Send message to client err := client.SendMessage(websocket.TextMessage, jsonMessage) if err != nil { diff --git a/internal/websocket/staleClients.go b/internal/websocket/staleClients.go new file mode 100644 index 0000000..9bb354b --- /dev/null +++ b/internal/websocket/staleClients.go @@ -0,0 +1,21 @@ +package websocket + +import ( + "time" +) + +// Check and remove stale clients +func RemoveStaleClients() { + ticker := time.NewTicker(30 * time.Second) + defer ticker.Stop() + + for range ticker.C { + mu.Lock() + for _, client := range Clients { + if client.IsStale() { + client.Conn.Close() + } + } + mu.Unlock() + } +}