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