36 lines
548 B
Go
36 lines
548 B
Go
package ws
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/coder/websocket"
|
|
"log"
|
|
"time"
|
|
)
|
|
|
|
func heartbeat(c *Client) {
|
|
ticker := time.NewTicker(30 * time.Second)
|
|
defer ticker.Stop()
|
|
|
|
defer func() {
|
|
c.Cancel()
|
|
_ = c.Conn.Close(websocket.StatusNormalClosure, "heartbeat stopped")
|
|
}()
|
|
|
|
for {
|
|
select {
|
|
case <-c.Ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
pingCtx, pingCancel := context.WithTimeout(c.Ctx, 5*time.Second)
|
|
err := c.Conn.Ping(pingCtx)
|
|
pingCancel()
|
|
|
|
if err != nil {
|
|
log.Println("Ping filed: ", err)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}
|