2024-10-21 07:24:20 +00:00
|
|
|
package websocket
|
2024-10-19 09:47:56 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"github.com/gorilla/websocket"
|
2024-10-21 06:16:26 +00:00
|
|
|
"time"
|
2024-10-28 08:33:05 +00:00
|
|
|
|
2024-11-04 19:33:25 +00:00
|
|
|
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
|
2024-10-28 08:33:05 +00:00
|
|
|
"git.smsvc.net/pomodoro/GoTomato/internal/shared"
|
2024-10-19 09:47:56 +00:00
|
|
|
)
|
|
|
|
|
2024-10-30 06:37:14 +00:00
|
|
|
// Sends continous messages to all connected WebSocket clients
|
2024-10-21 06:16:26 +00:00
|
|
|
func SendPermanentBroadCastMessage() {
|
2024-10-25 21:15:48 +00:00
|
|
|
tick := time.NewTicker(time.Second)
|
2024-11-20 13:07:00 +00:00
|
|
|
|
2024-10-21 06:16:26 +00:00
|
|
|
for {
|
|
|
|
// Marshal the message into JSON format
|
2024-10-29 17:46:00 +00:00
|
|
|
jsonMessage, err := json.Marshal(shared.State)
|
2024-10-19 09:47:56 +00:00
|
|
|
if err != nil {
|
2024-11-04 19:33:25 +00:00
|
|
|
helper.Logger.Error("Error marshalling message:", "msg", err)
|
2024-10-21 06:16:26 +00:00
|
|
|
return
|
|
|
|
}
|
2024-11-20 13:07:00 +00:00
|
|
|
|
2024-10-21 06:16:26 +00:00
|
|
|
// Iterate over all connected clients and broadcast the message
|
2024-11-20 20:51:12 +00:00
|
|
|
mu.Lock()
|
2024-10-21 07:24:20 +00:00
|
|
|
for _, client := range Clients {
|
2024-11-20 13:07:00 +00:00
|
|
|
// Send message to client
|
2024-11-21 07:43:02 +00:00
|
|
|
client.Conn.SetWriteDeadline(time.Now().Add(SEND_TIMEOUT * time.Second))
|
|
|
|
err := client.Conn.WriteMessage(websocket.TextMessage, jsonMessage)
|
2024-10-21 06:16:26 +00:00
|
|
|
if err != nil {
|
2024-11-20 13:07:00 +00:00
|
|
|
helper.Logger.Error("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients))
|
2024-10-21 06:16:26 +00:00
|
|
|
}
|
2024-10-19 09:47:56 +00:00
|
|
|
}
|
2024-11-20 20:51:12 +00:00
|
|
|
mu.Unlock()
|
2024-11-20 13:07:00 +00:00
|
|
|
|
2024-10-25 21:15:48 +00:00
|
|
|
<-tick.C
|
2024-10-19 09:47:56 +00:00
|
|
|
}
|
|
|
|
}
|