optimize ping/pong code

This commit is contained in:
Sebastian Mark 2024-11-20 20:39:32 +01:00
parent 62b6ab81a5
commit 18accba19a
2 changed files with 6 additions and 9 deletions

View file

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

View file

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