feat: 基本的websocket echo服务
This commit is contained in:
35
interval/ws/heartbeat.go
Normal file
35
interval/ws/heartbeat.go
Normal file
@ -0,0 +1,35 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user