From 32e00480f8b7c68bedc9f95a40196e67be591a51 Mon Sep 17 00:00:00 2001 From: Sebastian Mark Date: Wed, 20 Nov 2024 20:39:32 +0100 Subject: [PATCH] optimize ping/pong code --- internal/websocket/broadcast.go | 11 +++++------ pkg/models/client.go | 4 +--- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/internal/websocket/broadcast.go b/internal/websocket/broadcast.go index 7f0e1b2..b8333fd 100644 --- a/internal/websocket/broadcast.go +++ b/internal/websocket/broadcast.go @@ -22,17 +22,16 @@ func SendPermanentBroadCastMessage() { // Iterate over all connected clients and broadcast the message for _, client := range Clients { + if time.Now().Sub(client.LastPong) > (10 * time.Second) { + // Remove unresponsive client + client.Conn.Close() + } err := client.SendMessage(websocket.TextMessage, jsonMessage) if err != nil { helper.Logger.Info("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients)) } } - for _, client := range Clients { - if time.Now().Sub(client.LastPong) > (10 * time.Second) { - // Remove unresponsive client - client.Conn.Close() - } - } + <-tick.C } } diff --git a/pkg/models/client.go b/pkg/models/client.go index a758e77..00979c0 100644 --- a/pkg/models/client.go +++ b/pkg/models/client.go @@ -23,15 +23,13 @@ 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.SetPongHandler(func(s string) error { c.LastPong = time.Now() return nil }) - c.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second)) - c.Conn.WriteMessage(websocket.PingMessage, nil) c.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second)) + c.Conn.WriteMessage(websocket.PingMessage, nil) return c.Conn.WriteMessage(messageType, data) }