Compare commits

...

5 commits

4 changed files with 15 additions and 20 deletions

View file

@ -12,6 +12,7 @@ import (
// 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)
@ -24,9 +25,10 @@ func SendPermanentBroadCastMessage() {
mu.Lock()
for _, client := range Clients {
// Send message to client
err := client.SendMessage(websocket.TextMessage, jsonMessage)
client.Conn.SetWriteDeadline(time.Now().Add(SEND_TIMEOUT * time.Second))
err := client.Conn.WriteMessage(websocket.TextMessage, jsonMessage)
if err != nil {
helper.Logger.Info("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients))
helper.Logger.Error("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients))
}
}
mu.Unlock()

View file

@ -3,12 +3,13 @@ package websocket
import (
"time"
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
"github.com/gorilla/websocket"
)
func sendPing(client *models.WebsocketClient) bool {
client.Conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
client.Conn.SetWriteDeadline(time.Now().Add(SEND_TIMEOUT * time.Second))
err := client.Conn.WriteMessage(websocket.PingMessage, nil)
if err != nil {
@ -19,26 +20,21 @@ func sendPing(client *models.WebsocketClient) bool {
}
func isStale(client *models.WebsocketClient) bool {
return time.Since(client.LastPong) > (90 * time.Second)
return time.Since(client.LastPong) > (STALE_CLIENT_TIMEOUT * time.Second)
}
// Check and remove stale clients
func RemoveStaleClients() {
ticker := time.NewTicker(30 * time.Second)
ticker := time.NewTicker(STALE_CHECK_INTERVALL * time.Second)
defer ticker.Stop()
for range ticker.C {
mu.Lock()
for _, client := range Clients {
if !sendPing(client) {
client.Conn.Close()
delete(Clients, client.Conn.LocalAddr())
}
if isStale(client) {
if !sendPing(client) || isStale(client) {
client.Conn.Close()
delete(Clients, client.Conn.LocalAddr())
helper.Logger.Info("Removed stale client", "host", client.RealIP, "clients", len(Clients))
}
}
mu.Unlock()

View file

@ -0,0 +1,5 @@
package websocket
const SEND_TIMEOUT = 10
const STALE_CLIENT_TIMEOUT = 90
const STALE_CHECK_INTERVALL = 30

View file

@ -6,8 +6,6 @@ import (
"github.com/gorilla/websocket"
)
const TIMEOUT = 10
// Represents a command from the client (start/stop)
type ClientCommand struct {
Command string `json:"command"` // Command send to the server
@ -21,9 +19,3 @@ type WebsocketClient struct {
LastPong time.Time
RealIP string
}
// Sends a message to the websocket.
func (c *WebsocketClient) SendMessage(messageType int, data []byte) error {
c.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second))
return c.Conn.WriteMessage(messageType, data)
}