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-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-10-21 07:24:20 +00:00
|
|
|
for _, client := range Clients {
|
2024-11-20 19:15:24 +00:00
|
|
|
if time.Now().Sub(client.LastPong) > 10*time.Second {
|
|
|
|
// Remove unresponsive client
|
2024-11-20 18:53:40 +00:00
|
|
|
client.Conn.Close()
|
2024-11-20 13:07:00 +00:00
|
|
|
delete(Clients, client.Conn.LocalAddr())
|
2024-11-20 19:15:24 +00:00
|
|
|
helper.Logger.Info("Client timed out", "host", client.RealIP, "clients", len(Clients))
|
|
|
|
}
|
|
|
|
err := client.SendMessage(websocket.TextMessage, jsonMessage)
|
|
|
|
if err != nil {
|
2024-11-20 13:07:00 +00:00
|
|
|
helper.Logger.Info("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-10-25 21:15:48 +00:00
|
|
|
<-tick.C
|
2024-10-19 09:47:56 +00:00
|
|
|
}
|
|
|
|
}
|