feat: 基本广播服务

- 由Hub接收/push/{topic}的请求并解析信息体广播到对应的Client
This commit is contained in:
2025-12-17 14:49:59 +08:00
parent 53555a31c0
commit 1dbcc03e46
16 changed files with 245 additions and 191 deletions

View File

@ -2,10 +2,12 @@ package ws
import (
"context"
"errors"
"log"
"time"
"git.jinshen.cn/remilia/push-server/interval/protocol"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
)
// Client represents a connected client in the hub.
@ -13,28 +15,58 @@ type Client struct {
ID string
Conn *websocket.Conn
SendChan chan []byte
Hub *Hub
Ctx context.Context
Cancel context.CancelFunc
inited bool
}
func NewClient(id string, conn *websocket.Conn, parentCtx context.Context) *Client {
func NewClient(id string, conn *websocket.Conn, hub *Hub, parentCtx context.Context) *Client {
ctx, cancel := context.WithCancel(parentCtx)
return &Client{
ID: id,
Conn: conn,
SendChan: make(chan []byte, 32),
Ctx: ctx,
Cancel: cancel,
Hub: hub,
Ctx: ctx,
Cancel: cancel,
inited: false,
}
}
func (c *Client) ReadLoop() {
defer c.Close()
for {
var msg protocol.ControlMessage
err := wsjson.Read(c.Ctx, c.Conn, &msg)
if err != nil {
if websocket.CloseStatus(err) == websocket.StatusNormalClosure {
log.Println("WebSocket closed normally:", err)
} else {
log.Println("WebSocket read error:", err)
}
return
}
if err := msg.Validate(); err != nil {
_ = c.Conn.Close(websocket.StatusPolicyViolation, "invalid message")
return
}
if err := c.handleControlMessage(msg); err != nil {
return
}
}
}
// Write message to websocket connection.
func (c *Client) WriteMessage() {
defer func() {
_ = c.Conn.Close(websocket.StatusNormalClosure, "client writer closed")
}()
func (c *Client) WriteLoop() {
defer c.Close()
for {
select {
@ -44,11 +76,7 @@ func (c *Client) WriteMessage() {
if !ok {
return
}
writeCtx, cancel := context.WithTimeout(c.Ctx, 5*time.Second)
err := c.Conn.Write(writeCtx, websocket.MessageText, msg)
cancel()
err := wsjson.Write(c.Ctx, c.Conn, msg)
if err != nil {
log.Println("WebSocket write error:", err)
return
@ -56,3 +84,40 @@ func (c *Client) WriteMessage() {
}
}
}
func (c *Client) handleControlMessage(msg protocol.ControlMessage) error {
switch msg.Type {
case protocol.MsgInit:
if c.inited {
return errors.New("already initialized")
}
log.Printf("Client %s initializing with topics: %v", c.ID, msg.Topics)
c.Hub.RegisterClient(c)
for _, t := range msg.Topics {
c.Hub.Subscribe(protocol.Subscription{
ClientID: c.ID,
Topic: protocol.Topic(t),
})
}
c.inited = true
return nil
default:
if !c.inited {
return errors.New("client not initialized")
}
log.Println("Unknown control message type:", msg.Type)
return nil
}
}
func (c *Client) Close() {
c.Cancel()
c.Hub.UnregisterClient(c)
if c.Conn != nil {
_ = c.Conn.Close(websocket.StatusNormalClosure, "client closed")
}
}