Sebastian Mark
f13bdff03f
- rename tick to ticker for clarity
- change infinite loop to range over ticker channel
- add defer statement to stop the ticker properly
- remove unnecessary channel receive operation
🤖
37 lines
1,018 B
Go
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"
|
|
)
|
|
|
|
// Sends continous messages to all connected WebSocket clients
|
|
func SendPermanentBroadCastMessage() {
|
|
ticker := time.NewTicker(time.Second)
|
|
defer ticker.Stop()
|
|
|
|
for range ticker.C {
|
|
// 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
|
|
mu.Lock()
|
|
for _, client := range Clients {
|
|
// Send message to client
|
|
client.Conn.SetWriteDeadline(time.Now().Add(SEND_TIMEOUT * time.Second))
|
|
err := client.Conn.WriteMessage(websocket.TextMessage, jsonMessage)
|
|
if err != nil {
|
|
helper.Logger.Error("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients))
|
|
}
|
|
}
|
|
mu.Unlock()
|
|
}
|
|
}
|