2024-11-20 20:50:43 +00:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
2024-11-21 07:27:15 +00:00
|
|
|
|
|
|
|
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
|
|
|
"github.com/gorilla/websocket"
|
2024-11-20 20:50:43 +00:00
|
|
|
)
|
|
|
|
|
2024-11-21 07:27:15 +00:00
|
|
|
func sendPing(client *models.WebsocketClient) bool {
|
|
|
|
client.Conn.SetWriteDeadline(time.Now().Add(10 * 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) > (90 * time.Second)
|
|
|
|
}
|
|
|
|
|
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 07:27:15 +00:00
|
|
|
if !sendPing(client) {
|
|
|
|
client.Conn.Close()
|
|
|
|
delete(Clients, client.Conn.LocalAddr())
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
if 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()
|
|
|
|
}
|
|
|
|
}
|