feat: implement stale client removal after timeout

- add goroutine to remove stale clients from the connection pool
- update client struct to track `LastPong` time
- set write deadline for websocket connections
- move package variables and const to `vars.go`
- log additional information when broadcasting errors

🤖
This commit is contained in:
Sebastian Mark 2024-11-20 14:07:00 +01:00
parent e8e65c4f3a
commit ab2e8c161d
7 changed files with 75 additions and 21 deletions
internal/websocket

View file

@ -12,6 +12,7 @@ import (
// Sends continous messages to all connected WebSocket clients
func SendPermanentBroadCastMessage() {
tick := time.NewTicker(time.Second)
for {
// Marshal the message into JSON format
jsonMessage, err := json.Marshal(shared.State)
@ -19,14 +20,16 @@ func SendPermanentBroadCastMessage() {
helper.Logger.Error("Error marshalling message:", "msg", err)
return
}
// Iterate over all connected clients and broadcast the message
for _, client := range Clients {
// Send message to client
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
helper.Logger.Error("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients))
}
}
<-tick.C
}
}