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

58
interval/ws/client.go Normal file
View File

@ -0,0 +1,58 @@
package ws
import (
"context"
"log"
"time"
"github.com/coder/websocket"
)
// Client represents a connected client in the hub.
type Client struct {
ID string
Conn *websocket.Conn
SendChan chan []byte
Ctx context.Context
Cancel context.CancelFunc
}
func NewClient(id string, conn *websocket.Conn, parentCtx context.Context) *Client {
ctx, cancel := context.WithCancel(parentCtx)
return &Client{
ID: id,
Conn: conn,
SendChan: make(chan []byte, 32),
Ctx: ctx,
Cancel: cancel,
}
}
// Write message to websocket connection.
func (c *Client) WriteMessage() {
defer func() {
_ = c.Conn.Close(websocket.StatusNormalClosure, "client writer closed")
}()
for {
select {
case <-c.Ctx.Done():
return
case msg, ok := <-c.SendChan:
if !ok {
return
}
writeCtx, cancel := context.WithTimeout(c.Ctx, 5*time.Second)
err := c.Conn.Write(writeCtx, websocket.MessageText, msg)
cancel()
if err != nil {
log.Println("WebSocket write error:", err)
return
}
}
}
}