2024-11-20 20:50:43 +00:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
2024-11-21 06:29:05 +00:00
|
|
|
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
|
|
|
|
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
2024-11-20 20:50:43 +00:00
|
|
|
)
|
|
|
|
|
2024-11-21 06:29:05 +00:00
|
|
|
// 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
|
2024-11-21 06:29:05 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2024-11-20 20:50:43 +00:00
|
|
|
// 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:29:05 +00:00
|
|
|
// send ping and check for last pong
|
|
|
|
if !sendPing(client) || isStale(client) {
|
2024-11-20 20:50:43 +00:00
|
|
|
client.Conn.Close()
|
2024-11-20 21:01:56 +00:00
|
|
|
delete(Clients, client.Conn.LocalAddr())
|
2024-11-20 20:50:43 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
mu.Unlock()
|
|
|
|
}
|
|
|
|
}
|