GoTomato/internal/websocket/staleClients.go

49 lines
1,018 B
Go
Raw Normal View History

package websocket
import (
"time"
"github.com/gorilla/websocket"
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
)
// Checks if the websockets last Pong is recent
func isStale(client *models.WebsocketClient) bool {
return time.Since(client.LastPong) > (TIMEOUT * time.Second)
}
2024-11-21 06:34:50 +00:00
// send a Ping to the websocket client
func sendPing(client *models.WebsocketClient) bool {
client.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second))
err := client.Conn.WriteMessage(websocket.PingMessage, nil)
if err != nil {
return false
}
return true
}
// Check and remove stale clients
func RemoveStaleClients() {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for range ticker.C {
mu.Lock()
for _, client := range Clients {
2024-11-21 06:37:55 +00:00
// send ping
if !sendPing(client) {
client.Conn.Close()
delete(Clients, client.Conn.LocalAddr())
}
// check for last pong
if isStale(client) {
client.Conn.Close()
2024-11-20 21:01:56 +00:00
delete(Clients, client.Conn.LocalAddr())
}
}
mu.Unlock()
}
}