From 03d94d5999cc61a778e89fa2ab012e1777408d6e Mon Sep 17 00:00:00 2001 From: Sebastian Mark Date: Wed, 20 Nov 2024 19:53:40 +0100 Subject: [PATCH] another try to remove vanished clients --- internal/websocket/broadcast.go | 4 +--- pkg/models/client.go | 11 +++++------ 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/internal/websocket/broadcast.go b/internal/websocket/broadcast.go index ac03005..929cd26 100644 --- a/internal/websocket/broadcast.go +++ b/internal/websocket/broadcast.go @@ -9,8 +9,6 @@ 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) @@ -24,10 +22,10 @@ func SendPermanentBroadCastMessage() { // 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 { // Remove client on error + client.Conn.Close() delete(Clients, client.Conn.LocalAddr()) helper.Logger.Info("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients)) } diff --git a/pkg/models/client.go b/pkg/models/client.go index eef9663..3df5097 100644 --- a/pkg/models/client.go +++ b/pkg/models/client.go @@ -1,11 +1,13 @@ package models import ( - "github.com/gorilla/websocket" + "time" - "git.smsvc.net/pomodoro/GoTomato/internal/helper" + "github.com/gorilla/websocket" ) +const TIMEOUT = 10 + // Represents a command from the client (start/stop) type ClientCommand struct { Command string `json:"command"` // Command send to the server @@ -22,10 +24,7 @@ type WebsocketClient struct { // Sends a message to the websocket. // Automatically locks and unlocks the client mutex, to ensure that only one goroutine can write at a time. func (c *WebsocketClient) SendMessage(messageType int, data []byte) error { + c.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second)) err := c.Conn.WriteMessage(messageType, data) - if err != nil { - helper.Logger.Error("Error writing to WebSocket:", "msg", err) - c.Conn.Close() // Close the connection on error - } return err }