From 1e9b7fbb79be7434f53ba35c04ffff13d16e7319 Mon Sep 17 00:00:00 2001 From: Sebastian Mark Date: Thu, 21 Nov 2024 07:34:50 +0100 Subject: [PATCH] refactor: drop `SendMessage()` method --- internal/websocket/broadcast.go | 3 ++- internal/websocket/handle_connection.go | 2 ++ internal/websocket/staleClients.go | 3 +-- pkg/models/client.go | 8 -------- 4 files changed, 5 insertions(+), 11 deletions(-) diff --git a/internal/websocket/broadcast.go b/internal/websocket/broadcast.go index 2decfb0..14af2f4 100644 --- a/internal/websocket/broadcast.go +++ b/internal/websocket/broadcast.go @@ -24,7 +24,8 @@ func SendPermanentBroadCastMessage() { mu.Lock() for _, client := range Clients { // Send message to client - err := client.SendMessage(websocket.TextMessage, jsonMessage) + client.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second)) + err := client.Conn.WriteMessage(websocket.TextMessage, jsonMessage) if err != nil { helper.Logger.Info("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients)) } diff --git a/internal/websocket/handle_connection.go b/internal/websocket/handle_connection.go index cdb11cd..cee6564 100644 --- a/internal/websocket/handle_connection.go +++ b/internal/websocket/handle_connection.go @@ -15,6 +15,8 @@ import ( var Clients = make(map[net.Addr]*models.WebsocketClient) var mu sync.Mutex // Mutex to protect access to the Clients map +const TIMEOUT = 10 + // Upgrade HTTP requests to WebSocket connections var upgrader = websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true }, diff --git a/internal/websocket/staleClients.go b/internal/websocket/staleClients.go index d679950..bfa3de9 100644 --- a/internal/websocket/staleClients.go +++ b/internal/websocket/staleClients.go @@ -8,13 +8,12 @@ import ( "git.smsvc.net/pomodoro/GoTomato/pkg/models" ) -const TIMEOUT = 10 - // Checks if the websockets last Pong is recent func isStale(client *models.WebsocketClient) bool { return time.Since(client.LastPong) > (TIMEOUT * time.Second) } +// send a Ping to the websocket client func sendPing(client *models.WebsocketClient) bool { client.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second)) err := client.Conn.WriteMessage(websocket.PingMessage, nil) diff --git a/pkg/models/client.go b/pkg/models/client.go index ae85a94..9d5dbdb 100644 --- a/pkg/models/client.go +++ b/pkg/models/client.go @@ -6,8 +6,6 @@ import ( "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 @@ -21,9 +19,3 @@ type WebsocketClient struct { LastPong time.Time RealIP string } - -// Sends a message to the websocket. -func (c *WebsocketClient) SendMessage(messageType int, data []byte) error { - c.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second)) - return c.Conn.WriteMessage(messageType, data) -}