Documentation
¶
Overview ¶
Package wsutil 提供通用 WebSocket 基础设施。
Broadcaster 是基于房间的广播器,支持多房间、自动清理空房间、容错广播。 通过 Conn 接口解耦,不依赖具体的 websocket 库实现。
用法:
b := wsutil.NewBroadcaster()
defer b.Close()
// 客户端加入房间
b.Register("room:123", conn)
// 广播事件
b.BroadcastEvent("room:123", wsutil.Event{Type: "progress", Data: data})
// 查询房间状态
count := b.GetRoomCount("room:123")
rooms := b.GetRooms()
Index ¶
- Constants
- type Broadcaster
- func (b *Broadcaster) Broadcast(room string, message []byte)
- func (b *Broadcaster) BroadcastEvent(room string, event Event)
- func (b *Broadcaster) Close()
- func (b *Broadcaster) GetRoomCount(room string) int
- func (b *Broadcaster) GetRooms() []string
- func (b *Broadcaster) GetTotalConnections() int
- func (b *Broadcaster) Register(room string, conn Conn)
- func (b *Broadcaster) Unregister(room string, conn Conn)
- type Conn
- type Event
Constants ¶
View Source
const (
// TextMessage 表示文本消息类型(与 websocket.TextMessage 一致)。
TextMessage = 1
)
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Broadcaster ¶
type Broadcaster struct {
// contains filtered or unexported fields
}
Broadcaster 是基于房间的 WebSocket 广播器。 支持多房间、自动清理空房间、容错广播。
用法:
b := wsutil.NewBroadcaster()
defer b.Close()
// 客户端加入房间
b.Register("review:123", conn)
// 广播事件
b.BroadcastEvent("review:123", wsutil.Event{Type: "progress", Data: progress})
func (*Broadcaster) Broadcast ¶
func (b *Broadcaster) Broadcast(room string, message []byte)
Broadcast 向指定房间广播原始字节消息。
func (*Broadcaster) BroadcastEvent ¶
func (b *Broadcaster) BroadcastEvent(room string, event Event)
BroadcastEvent 向指定房间广播事件(自动序列化为 JSON 并添加时间戳)。
func (*Broadcaster) GetRoomCount ¶
func (b *Broadcaster) GetRoomCount(room string) int
GetRoomCount 返回指定房间的连接数。
func (*Broadcaster) GetTotalConnections ¶
func (b *Broadcaster) GetTotalConnections() int
GetTotalConnections 返回所有房间的总连接数。
func (*Broadcaster) Register ¶
func (b *Broadcaster) Register(room string, conn Conn)
Register 将连接加入指定房间。
func (*Broadcaster) Unregister ¶
func (b *Broadcaster) Unregister(room string, conn Conn)
Unregister 将连接从指定房间移除。 同一连接可注册多个房间;物理连接仅在最后一个房间移除时关闭。
Click to show internal directories.
Click to hide internal directories.