feat: 基本广播服务
- 由Hub接收/push/{topic}的请求并解析信息体广播到对应的Client
This commit is contained in:
69
cmd/client/main.go
Normal file
69
cmd/client/main.go
Normal file
@ -0,0 +1,69 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
|
||||
"git.jinshen.cn/remilia/push-server/interval/protocol"
|
||||
)
|
||||
|
||||
func main() {
|
||||
log.Println("This is a test client.")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
c, _, err := websocket.Dial(ctx, "ws://localhost:8080/ws", nil)
|
||||
if err != nil {
|
||||
log.Fatal("dial error:", err)
|
||||
return
|
||||
}
|
||||
defer func() { _ = c.CloseNow() }()
|
||||
|
||||
initMsg := protocol.ControlMessage{
|
||||
Type: protocol.MsgInit,
|
||||
Topics: []protocol.Topic{"news", "sports"},
|
||||
}
|
||||
|
||||
log.Println("Sending init message:", initMsg)
|
||||
|
||||
err = wsjson.Write(ctx, c, initMsg)
|
||||
if err != nil {
|
||||
if websocket.CloseStatus(err) != websocket.StatusNormalClosure {
|
||||
log.Printf("init write failed: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// typ, msg, err := c.Read(ctx)
|
||||
// if err != nil {
|
||||
// log.Println("read error:", err)
|
||||
// return
|
||||
// }
|
||||
//
|
||||
// switch typ {
|
||||
// case websocket.MessageText:
|
||||
// log.Printf("Received text message: %s", string(msg))
|
||||
// case websocket.MessageBinary:
|
||||
// log.Printf("Received binary message: %v", msg)
|
||||
// }
|
||||
go ReadBroadCastLoop(ctx, c)
|
||||
<-ctx.Done()
|
||||
|
||||
_ = c.Close(websocket.StatusNormalClosure, "test client finished")
|
||||
}
|
||||
|
||||
func ReadBroadCastLoop(ctx context.Context, c *websocket.Conn) {
|
||||
for {
|
||||
// var msg protocol.BroadcastMessage
|
||||
var msg []byte
|
||||
if err := wsjson.Read(ctx, c, &msg); err != nil {
|
||||
log.Println("read broadcast error:", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("Received broadcast message:", string(msg))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user