Compare commits

..

No commits in common. "2d5fa692d3cf36e3510a6084dc36dc4ae44481be" and "2faa95c162f1118be5767451b8f23c4323472e2d" have entirely different histories.

4 changed files with 27 additions and 29 deletions

View file

@ -12,7 +12,6 @@ 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)
@ -25,9 +24,7 @@ func SendPermanentBroadCastMessage() {
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)
err := client.SendMessage(websocket.TextMessage, jsonMessage)
if err != nil {
helper.Logger.Info("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients))
}

View file

@ -2,35 +2,17 @@ package websocket
import (
"time"
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
"github.com/gorilla/websocket"
)
func sendPing(client *models.WebsocketClient) bool {
client.Conn.SetWriteDeadline(time.Now().Add(SEND_TIMEOUT * time.Second))
err := client.Conn.WriteMessage(websocket.PingMessage, nil)
if err != nil {
return false
}
return true
}
func isStale(client *models.WebsocketClient) bool {
return time.Since(client.LastPong) > (STALE_CLIENT_TIMEOUT * time.Second)
}
// Check and remove stale clients
func RemoveStaleClients() {
ticker := time.NewTicker(CHECK_INTERVALL * time.Second)
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for range ticker.C {
mu.Lock()
for _, client := range Clients {
if !sendPing(client) || isStale(client) {
if client.IsStale() {
client.Conn.Close()
delete(Clients, client.Conn.LocalAddr())
}

View file

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

View file

@ -6,6 +6,8 @@ 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
@ -19,3 +21,25 @@ 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))
err := c.Conn.WriteMessage(websocket.PingMessage, nil)
if err != nil {
return err
}
c.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second))
err = c.Conn.WriteMessage(messageType, data)
if err != nil {
return err
}
return nil
}
// Checks if the websockets last Pong is recent
func (c *WebsocketClient) IsStale() bool {
return time.Since(c.LastPong) > (TIMEOUT * time.Second)
}