GoTomato/internal/websocket/staleClients.go

41 lines
841 B
Go
Raw Normal View History

package websocket
import (
"time"
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
"github.com/gorilla/websocket"
)
func sendPing(client *models.WebsocketClient) bool {
2024-11-21 07:44:50 +00:00
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 {
2024-11-21 07:44:50 +00:00
return time.Since(client.LastPong) > (STALE_CLIENT_TIMEOUT * time.Second)
}
// Check and remove stale clients
func RemoveStaleClients() {
2024-11-21 07:44:50 +00:00
ticker := time.NewTicker(CHECK_INTERVALL * time.Second)
defer ticker.Stop()
for range ticker.C {
mu.Lock()
for _, client := range Clients {
2024-11-21 07:47:58 +00:00
if !sendPing(client) || isStale(client) {
client.Conn.Close()
2024-11-20 21:01:56 +00:00
delete(Clients, client.Conn.LocalAddr())
}
}
mu.Unlock()
}
}