move stale client check to RemoveStaleClients()

This commit is contained in:
Sebastian Mark 2024-11-20 21:50:43 +01:00
parent f4b1e7c808
commit bf9b818940
3 changed files with 22 additions and 5 deletions

View file

@ -54,6 +54,7 @@ func Start() {
r := http.NewServeMux() r := http.NewServeMux()
r.HandleFunc("/", websocket.HandleConnection) r.HandleFunc("/", websocket.HandleConnection)
go websocket.SendPermanentBroadCastMessage() go websocket.SendPermanentBroadCastMessage()
go websocket.RemoveStaleClients()
helper.Logger.Info("GoTomato started", "version", metadata.GoTomatoVersion) helper.Logger.Info("GoTomato started", "version", metadata.GoTomatoVersion)
helper.Logger.Info("Websocket listening", "address", listen) helper.Logger.Info("Websocket listening", "address", listen)

View file

@ -22,11 +22,6 @@ func SendPermanentBroadCastMessage() {
// Iterate over all connected clients and broadcast the message // Iterate over all connected clients and broadcast the message
for _, client := range Clients { for _, client := range Clients {
// Remove unresponsive client
if client.IsStale() {
client.Conn.Close()
continue
}
// Send message to client // Send message to client
err := client.SendMessage(websocket.TextMessage, jsonMessage) err := client.SendMessage(websocket.TextMessage, jsonMessage)
if err != nil { if err != nil {

View file

@ -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()
}
}