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