another try to remove vanished clients

This commit is contained in:
Sebastian Mark 2024-11-20 19:53:40 +01:00
parent 75b3ae87d6
commit 03d94d5999
2 changed files with 6 additions and 9 deletions

View file

@ -9,8 +9,6 @@ import (
"git.smsvc.net/pomodoro/GoTomato/internal/shared"
)
const TIMEOUT = 10
// Sends continous messages to all connected WebSocket clients
func SendPermanentBroadCastMessage() {
tick := time.NewTicker(time.Second)
@ -24,10 +22,10 @@ func SendPermanentBroadCastMessage() {
// Iterate over all connected clients and broadcast the message
for _, client := range Clients {
client.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second))
err := client.SendMessage(websocket.TextMessage, jsonMessage)
if err != nil {
// Remove client on error
client.Conn.Close()
delete(Clients, client.Conn.LocalAddr())
helper.Logger.Info("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients))
}

View file

@ -1,11 +1,13 @@
package models
import (
"github.com/gorilla/websocket"
"time"
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
"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
@ -22,10 +24,7 @@ type WebsocketClient struct {
// Sends a message to the websocket.
// Automatically locks and unlocks the client mutex, to ensure that only one goroutine can write at a time.
func (c *WebsocketClient) SendMessage(messageType int, data []byte) error {
c.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second))
err := c.Conn.WriteMessage(messageType, data)
if err != nil {
helper.Logger.Error("Error writing to WebSocket:", "msg", err)
c.Conn.Close() // Close the connection on error
}
return err
}