GoTomato/internal/websocket/broadcast.go
Sebastian Mark 75b3ae87d6 feat: remove client from active connections after write deadline
- add a constant for timeout duration in seconds
- set write deadline for client connections
- remove client from active connections on error
- log additional information when broadcasting fails

🤖
2024-11-21 18:49:58 +01:00

37 lines
1,018 B
Go

package websocket
import (
"encoding/json"
"github.com/gorilla/websocket"
"time"
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
"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)
for {
// Marshal the message into JSON format
jsonMessage, err := json.Marshal(shared.State)
if err != nil {
helper.Logger.Error("Error marshalling message:", "msg", err)
return
}
// 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
delete(Clients, client.Conn.LocalAddr())
helper.Logger.Info("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients))
}
}
<-tick.C
}
}