fix: remove client from active connections after write deadline

- 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

🤖
This commit is contained in:
Sebastian Mark 2024-11-20 14:07:00 +01:00
parent e8e65c4f3a
commit 370469de36
2 changed files with 8 additions and 2 deletions

View file

@ -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

View file

@ -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