Documentation
¶
Overview ¶
Package websocket 定义通信传输层接口.
对应原项目中同名模块的功能. 引擎不关心底层用什么协议通信,通过接口抽象.
实现:
- WebSocketTransport: 基于标准库的 WebSocket 实现(见 websocket.go)
Index ¶
Constants ¶
const ( MessageText = 1 // 文本消息 MessageBinary = 2 // 二进制消息 )
MessageType 定义消息类型常量.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type MessageHandler ¶
MessageHandler 是消息回调函数类型. msgType 是消息类型(MessageText 或 MessageBinary),data 是消息内容.
type Transport ¶
type Transport interface {
// Connect 建立连接.
// ctx 用于控制连接的生命周期.
Connect(ctx context.Context) error
// Send 发送数据.
// 如果连接断开且实现支持缓冲,数据可能被缓存等待重连.
Send(data []byte) error
// Receive 返回接收数据的 channel.
// 消费者通过 for range 读取收到的消息.
// channel 关闭表示连接已终止.
Receive() <-chan []byte
// Close 优雅关闭连接.
Close() error
}
Transport 是传输层接口. 所有传输实现(WebSocket,stdio,HTTP SSE 等)都需要满足此接口.
type WebSocketConfig ¶
type WebSocketConfig struct {
// URL WebSocket 服务器地址(ws:// 或 wss://)
URL string
// MaxMessageSize 最大消息大小(字节),默认 1MB
MaxMessageSize int
// PingInterval Ping 心跳间隔,默认 30 秒
PingInterval time.Duration
// AutoReconnect 是否启用自动重连
AutoReconnect bool
// MaxReconnectAttempts 最大重连次数,默认 10
MaxReconnectAttempts int
// BufferSize 消息缓冲区大小,默认 256
BufferSize int
// OnMessage 消息回调(可选)
OnMessage func(msgType int, data []byte)
}
WebSocketConfig 是 WebSocket 传输层的配置.
type WebSocketConn ¶
type WebSocketConn struct {
// contains filtered or unexported fields
}
WebSocketConn 是服务端的 WebSocket 连接.
func UpgradeHTTP ¶
func UpgradeHTTP(w http.ResponseWriter, r *http.Request) (*WebSocketConn, error)
UpgradeHTTP 将 HTTP 请求升级为 WebSocket 连接(服务端用). 使用 net/http 的 Hijack 接口接管底层 TCP 连接. 返回一个 WebSocketConn 用于收发消息.
func (*WebSocketConn) ReadMessage ¶
func (c *WebSocketConn) ReadMessage() (int, []byte, error)
ReadMessage 读取一条消息.
func (*WebSocketConn) WriteMessage ¶
func (c *WebSocketConn) WriteMessage(opcode int, payload []byte) error
WriteMessage 写入一条消息(服务端帧不需要 mask).
type WebSocketTransport ¶
type WebSocketTransport struct {
// contains filtered or unexported fields
}
WebSocketTransport 是 WebSocket 传输层实现.
func NewWebSocket ¶
func NewWebSocket(cfg WebSocketConfig) *WebSocketTransport
NewWebSocket 创建 WebSocket 传输层实例.
func (*WebSocketTransport) Close ¶
func (ws *WebSocketTransport) Close() error
Close 优雅关闭 WebSocket 连接. 发送 Close 帧并等待对端确认.
func (*WebSocketTransport) Connect ¶
func (ws *WebSocketTransport) Connect(ctx context.Context) error
Connect 建立 WebSocket 连接. 执行 HTTP 升级握手,然后切换到 WebSocket 帧协议.
func (*WebSocketTransport) Receive ¶
func (ws *WebSocketTransport) Receive() <-chan []byte
Receive 返回接收消息的 channel.
func (*WebSocketTransport) Send ¶
func (ws *WebSocketTransport) Send(data []byte) error
Send 发送消息. 如果连接断开且启用了自动重连,消息会被缓存.
func (*WebSocketTransport) SendBinary ¶
func (ws *WebSocketTransport) SendBinary(data []byte) error
SendBinary 发送二进制消息.