Documentation
¶
Overview ¶
Package session 提供基于 WebSocket 的有状态会话高阶封装。
在 pkg/ws 的薄封装之上,补齐长连接生产级所需的:
- 双 goroutine 读写模型:读循环(主)与写循环(子)分离,所有写串行化, 避免对 conn 的并发写(coder/websocket 允许并发读写,但同方向需串行);
- 心跳:写循环按周期发 Ping(带超时),CloseRead 在后台处理 pong/close 控制帧; 读循环的 ctx 在连接断开时自动取消,用于检测半开;
- 关闭握手:Close 只发一次 close 帧,CloseRead 返回的 ctx 取消即代表对端断开;
- 写超时保护:每条写用独立带超时的 ctx,慢客户端不拖垮会话。
Consume/processOutgoing/pingNow, 适配 coder/websocket 的 context-based API。
使用:
mux.Handle("/ws", ws.Handler(session.Accept(myHandler, opts...)))
其中 myHandler 实现 session.Handler,在 OnMessage 里读消息、用 Send 投递写。
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Handler ¶
type Handler interface {
// OnOpen 在握手成功、会话就绪后调用一次。返回 error 立即关闭会话。
OnOpen(s *Session) error
// OnMessage 在收到一条客户端消息时调用。返回 error 关闭会话。
OnMessage(s *Session, typ MessageType, data []byte) error
// OnClose 在会话结束(任何原因)时调用一次,用于清理。
OnClose(s *Session, reason string)
}
Handler 由业务实现,定义会话生命周期。 OnOpen/OnMessage/OnClose 都在读循环 goroutine 内串行调用,故业务状态可无锁。
type Option ¶
type Option func(*config)
Option 配置 Accept 行为。
func WithMaxMessageSize ¶
WithMaxMessageSize 设置单条消息读取上限(字节),默认 0=不限。
func WithPingBackoff ¶
WithPingBackoff 设置"每收 N 条消息才 ping 一次"的阈值,默认 20。 业务流量大时少 ping,省带宽。
func WithPingPeriod ¶
WithPingPeriod 设置主动 ping 周期。默认 54s(小于多数网关 60s 空闲)。 <=0 不主动 ping(此时也不检测半开)。
func WithPingTimeout ¶
WithPingTimeout 设置单次 ping 的等待超时(等 pong),默认 5s。 ping 超时即视为半开,关闭会话。
func WithWriteTimeout ¶
WithWriteTimeout 设置每条业务写的超时,默认 10s。
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session 是一个有状态 WebSocket 会话。零值不可用,由 Accept 创建。
Click to show internal directories.
Click to hide internal directories.