GoTomato/internal/websocket/broadcast.go

39 lines
991 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)
2024-11-21 07:44:50 +00:00
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
2024-11-20 20:51:12 +00:00
mu.Lock()
for _, client := range Clients {
2024-11-20 20:22:12 +00:00
// Send message to client
client.Conn.SetWriteDeadline(time.Now().Add(SEND_TIMEOUT * time.Second))
err := client.Conn.WriteMessage(websocket.TextMessage, jsonMessage)
2024-11-20 19:39:32 +00:00
if err != nil {
helper.Logger.Info("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients))
}
}
2024-11-20 20:51:12 +00:00
mu.Unlock()
2024-11-20 19:39:32 +00:00
<-tick.C
}
}