59 lines
1.0 KiB
Go
59 lines
1.0 KiB
Go
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
|
|
}
|
|
}
|
|
}
|
|
}
|