move ping/ping from SendMessage() to RemoveStaleClients()
This commit is contained in:
parent
2faa95c162
commit
ed67e9bc69
2 changed files with 23 additions and 18 deletions
|
@ -2,8 +2,28 @@ package websocket
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
|
||||||
|
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const TIMEOUT = 10
|
||||||
|
|
||||||
|
// Checks if the websockets last Pong is recent
|
||||||
|
func isStale(client *models.WebsocketClient) bool {
|
||||||
|
return time.Since(client.LastPong) > (TIMEOUT * time.Second)
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
// Check and remove stale clients
|
||||||
func RemoveStaleClients() {
|
func RemoveStaleClients() {
|
||||||
ticker := time.NewTicker(30 * time.Second)
|
ticker := time.NewTicker(30 * time.Second)
|
||||||
|
@ -12,7 +32,8 @@ func RemoveStaleClients() {
|
||||||
for range ticker.C {
|
for range ticker.C {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
for _, client := range Clients {
|
for _, client := range Clients {
|
||||||
if client.IsStale() {
|
// send ping and check for last pong
|
||||||
|
if !sendPing(client) || isStale(client) {
|
||||||
client.Conn.Close()
|
client.Conn.Close()
|
||||||
delete(Clients, client.Conn.LocalAddr())
|
delete(Clients, client.Conn.LocalAddr())
|
||||||
}
|
}
|
||||||
|
|
|
@ -25,21 +25,5 @@ type WebsocketClient struct {
|
||||||
// Sends a message to the websocket.
|
// Sends a message to the websocket.
|
||||||
func (c *WebsocketClient) SendMessage(messageType int, data []byte) error {
|
func (c *WebsocketClient) SendMessage(messageType int, data []byte) error {
|
||||||
c.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second))
|
c.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second))
|
||||||
err := c.Conn.WriteMessage(websocket.PingMessage, nil)
|
return c.Conn.WriteMessage(messageType, data)
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
c.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second))
|
|
||||||
err = c.Conn.WriteMessage(messageType, data)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Checks if the websockets last Pong is recent
|
|
||||||
func (c *WebsocketClient) IsStale() bool {
|
|
||||||
return time.Since(c.LastPong) > (TIMEOUT * time.Second)
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue