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 {
|
2024-11-21 07:44:50 +00:00
|
|
|
client.Conn.SetWriteDeadline(time.Now().Add(SEND_TIMEOUT * time.Second))
|
2024-11-21 07:27:15 +00:00
|
|
|
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)
|
2024-11-21 07:27:15 +00:00
|
|
|
}
|
|
|
|
|
2024-11-20 20:50:43 +00:00
|
|
|
// Check and remove stale clients
|
|
|
|
func RemoveStaleClients() {
|
2024-11-21 07:44:50 +00:00
|
|
|
ticker := time.NewTicker(STALE_CHECK_INTERVALL * time.Second)
|
2024-11-20 20:50:43 +00:00
|
|
|
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) {
|
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()
|
|
|
|
}
|
|
|
|
}
|