GoTomato/internal/websocket/broadcast.go

36 lines
951 B
Go
Raw Normal View History

package websocket
import (
"encoding/json"
"github.com/gorilla/websocket"
"time"
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
"git.smsvc.net/pomodoro/GoTomato/internal/shared"
)
2024-10-30 06:37:14 +00:00
// 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 {
err := client.SendMessage(websocket.TextMessage, jsonMessage)
if err != nil {
// Remove client on error
2024-11-20 18:53:40 +00:00
client.Conn.Close()
delete(Clients, client.Conn.LocalAddr())
helper.Logger.Info("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients))
}
}
<-tick.C
}
}