feat: 基本的websocket echo服务

This commit is contained in:
2025-12-17 12:03:06 +08:00
parent b824dc3792
commit 1bc9c6a924
11 changed files with 242 additions and 29 deletions

35
interval/ws/heartbeat.go Normal file
View 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
}
}
}
}