Documentation
¶
Index ¶
- Variables
- func Recovery(logger Logger)
- func SetBufferThreshold(x uint32)
- type Broadcaster
- type BuiltinEventHandler
- func (b BuiltinEventHandler) OnClose(socket *Conn, err error)
- func (b BuiltinEventHandler) OnMessage(socket *Conn, message *Message)
- func (b BuiltinEventHandler) OnOpen(socket *Conn)
- func (b BuiltinEventHandler) OnPing(socket *Conn, payload []byte)
- func (b BuiltinEventHandler) OnPong(socket *Conn, payload []byte)
- type ClientOption
- type CloseError
- type ConcurrentMap
- func (c *ConcurrentMap[K, V]) Delete(key K)
- func (c *ConcurrentMap[K, V]) GetSharding(key K) *Map[K, V]
- func (c *ConcurrentMap[K, V]) Len() int
- func (c *ConcurrentMap[K, V]) Load(key K) (value V, ok bool)
- func (c *ConcurrentMap[K, V]) Range(f func(key K, value V) bool)
- func (c *ConcurrentMap[K, V]) Store(key K, value V)
- type Config
- type Conn
- func (c *Conn) Async(f func())
- func (c *Conn) LocalAddr() net.Addr
- func (c *Conn) NetConn() net.Conn
- func (c *Conn) ReadLoop()
- func (c *Conn) ReadMessage() (*Message, error)
- func (c *Conn) RemoteAddr() net.Addr
- func (c *Conn) Session() SessionStorage
- func (c *Conn) SetDeadline(t time.Time) error
- func (c *Conn) SetNoDelay(noDelay bool) error
- func (c *Conn) SetReadDeadline(t time.Time) error
- func (c *Conn) SetWriteDeadline(t time.Time) error
- func (c *Conn) SubProtocol() string
- func (c *Conn) UpdateHandler(handler EventHandler)
- func (c *Conn) WriteAsync(opcode Opcode, payload []byte, callback func(error))
- func (c *Conn) WriteClose(code uint16, reason []byte) error
- func (c *Conn) WriteMessage(opcode Opcode, payload []byte) error
- func (c *Conn) WritePing(payload []byte) error
- func (c *Conn) WritePong(payload []byte) error
- func (c *Conn) WriteString(s string) error
- func (c *Conn) Writev(opcode Opcode, payloads ...[]byte) error
- func (c *Conn) WritevAsync(opcode Opcode, payloads [][]byte, callback func(error))
- type Dialer
- type EventHandler
- type Logger
- type Map
- type Message
- type Opcode
- type Server
- type ServerOption
- type SessionStorage
- type Upgrader
Constants ¶
This section is empty.
Variables ¶
var ( // Failure to pass forensic authentication ErrUnauthorized = errors.New("unauthorized") // ErrHandshake 握手错误, 请求头未通过校验 // Handshake error, request header does not pass checksum. ErrHandshake = errors.New("handshake error") // ErrSubprotocolNegotiation 子协议协商失败 // Sub-protocol negotiation failed ErrSubprotocolNegotiation = errors.New("sub-protocol negotiation failed") // ErrTextEncoding 文本消息编码错误(必须是utf8编码) // Text message encoding error (must be utf8) ErrTextEncoding = errors.New("invalid text encoding") // ErrMessageTooLarge 消息体积过大 // message is too large ErrMessageTooLarge = errors.New("message too large") // ErrConnClosed 连接已关闭 // Connection closed ErrConnClosed = net.ErrClosed // ErrUnsupportedProtocol 不支持的网络协议 // Unsupported network protocols ErrUnsupportedProtocol = errors.New("unsupported protocol") )
Functions ¶
func Recovery ¶
func Recovery(logger Logger)
Recovery 异常恢复,并记录错误信息 Exception recovery with logging of error messages
func SetBufferThreshold ¶
func SetBufferThreshold(x uint32)
SetBufferThreshold 设置buffer阈值, x=pow(2,n), 超过x个字节的buffer不会被回收 Set the buffer threshold, x=pow(2,n), that buffers larger than x bytes are not reclaimed.
Types ¶
type Broadcaster ¶
type Broadcaster struct {
// contains filtered or unexported fields
}
func NewBroadcaster ¶
func NewBroadcaster(opcode Opcode, payload []byte) *Broadcaster
NewBroadcaster 创建广播器 Creates a broadcaster 相比循环调用 WriteAsync, Broadcaster 只会压缩一次消息, 可以节省大量 CPU 开销. Instead of calling WriteAsync in a loop, Broadcaster compresses the message only once, saving a lot of CPU overhead.
func (*Broadcaster) Broadcast ¶
func (c *Broadcaster) Broadcast(socket *Conn) error
Broadcast 广播 向客户端发送广播消息 Send a broadcast message to a client.
func (*Broadcaster) Close ¶
func (c *Broadcaster) Close() error
Close 释放资源 Releases resources 在完成所有 Broadcast 调用之后执行 Close 方法释放资源。 Call the Close method after all the Broadcasts have been completed to release the resources.
type BuiltinEventHandler ¶
type BuiltinEventHandler struct{}
func (BuiltinEventHandler) OnClose ¶
func (b BuiltinEventHandler) OnClose(socket *Conn, err error)
func (BuiltinEventHandler) OnMessage ¶
func (b BuiltinEventHandler) OnMessage(socket *Conn, message *Message)
func (BuiltinEventHandler) OnOpen ¶
func (b BuiltinEventHandler) OnOpen(socket *Conn)
func (BuiltinEventHandler) OnPing ¶
func (b BuiltinEventHandler) OnPing(socket *Conn, payload []byte)
func (BuiltinEventHandler) OnPong ¶
func (b BuiltinEventHandler) OnPong(socket *Conn, payload []byte)
type ClientOption ¶
type ClientOption struct {
Logger Logger
// For custom SessionStorage implementations
NewSession func() SessionStorage
// The default is to return the net.Dialer instance.
// Can also be used to set a proxy, for example:
// NewDialer: func() (proxy.Dialer, error) {
// return proxy.SOCKS5("tcp", "127.0.0.1:1080", nil, nil)
// },
NewDialer func() (Dialer, error)
// TLS configuration
TlsConfig *tls.Config
// Extra request headers
RequestHeader http.Header
// Recovery function
Recovery func(logger Logger)
// Server address, e.g., wss://example.com/connect
Addr string
// Maximum payload size for reading
ReadMaxPayloadSize int
// Maximum payload size for writing
WriteMaxPayloadSize int
// Read buffer size
ReadBufferSize int
// Handshake timeout duration
HandshakeTimeout time.Duration
// Parallel goroutine limit
ParallelGolimit int
// Whether UTF-8 check is enabled
CheckUtf8Enabled bool
// Whether parallel processing is enabled
ParallelEnabled bool
}
ClientOption 客户端配置 Client configurations
type CloseError ¶
type CloseError struct {
// Close reason, providing a detailed description of the closure
Reason []byte
// Close code, indicating the reason for closing the connection
Code uint16
}
func (*CloseError) Error ¶
func (c *CloseError) Error() string
Error 关闭错误的描述 Returns a description of the close error
type ConcurrentMap ¶
type ConcurrentMap[K comparable, V any] struct { // contains filtered or unexported fields }
ConcurrentMap 并发安全的映射结构 concurrency-safe map structure
func NewConcurrentMap ¶
func NewConcurrentMap[K comparable, V any](size ...uint64) *ConcurrentMap[K, V]
NewConcurrentMap 创建一个新的并发安全映射 creates a new concurrency-safe map arg0 表示分片的数量;arg1 表示分片的初始化容量 arg0 represents the number of shardings; arg1 represents the initialized capacity of a sharding.
func (*ConcurrentMap[K, V]) Delete ¶
func (c *ConcurrentMap[K, V]) Delete(key K)
Delete 删除键对应的值 Delete deletes the value for a key
func (*ConcurrentMap[K, V]) GetSharding ¶
func (c *ConcurrentMap[K, V]) GetSharding(key K) *Map[K, V]
GetSharding 返回一个键的分片映射 returns a map sharding for a key 分片中的操作是无锁的,需要手动加锁 The operations inside the sharding are lockless and need to be locked manually.
func (*ConcurrentMap[K, V]) Len ¶
func (c *ConcurrentMap[K, V]) Len() int
Len 返回映射中的元素数量 Len returns the number of elements in the map
func (*ConcurrentMap[K, V]) Load ¶
func (c *ConcurrentMap[K, V]) Load(key K) (value V, ok bool)
Load 返回映射中键对应的值,如果不存在则返回 nil returns the value stored in the map for a key, or nil if no value is present ok 结果表示是否在映射中找到了值 The ok result indicates whether the value was found in the map
func (*ConcurrentMap[K, V]) Range ¶
func (c *ConcurrentMap[K, V]) Range(f func(key K, value V) bool)
Range 遍历 如果 f 返回 false,遍历停止 If f returns false, range stops the iteration
func (*ConcurrentMap[K, V]) Store ¶
func (c *ConcurrentMap[K, V]) Store(key K, value V)
Store 设置键对应的值 sets the value for a key
type Config ¶
type Config struct {
// Logging tools
Logger Logger
// Message callback (OnMessage) recovery program
Recovery func(logger Logger)
// Maximum read message content length
ReadMaxPayloadSize int
// Size of the read buffer
ReadBufferSize int
// Maximum length of written message content
WriteMaxPayloadSize int
// Limit on the number of concurrent goroutines used for parallel message processing (single connection)
ParallelGolimit int
// Whether to check the text utf8 encoding, turn off the performance will be better
CheckUtf8Enabled bool
// Whether to enable parallel message processing
ParallelEnabled bool
// contains filtered or unexported fields
}
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn WebSocket连接 WebSocket connection
func NewClient ¶
func NewClient(handler EventHandler, option *ClientOption) (*Conn, *http.Response, error)
NewClient 创建一个新的 WebSocket 客户端连接 Creates a new WebSocket client connection
func NewClientFromConn ¶
func NewClientFromConn(handler EventHandler, option *ClientOption, conn net.Conn) (*Conn, *http.Response, error)
NewClientFromConn 通过外部连接创建客户端, 支持 TCP/KCP/Unix Domain Socket Create new client via external connection, supports TCP/KCP/Unix Domain Socket.
func (*Conn) Async ¶
func (c *Conn) Async(f func())
Async 异步 将任务加入发送队列(并发度为1), 执行异步操作 注意: 不要加入长时间阻塞的任务 Add the task to the send queue (concurrency 1), perform asynchronous operation. Note: Don't add tasks that are blocking for a long time.
func (*Conn) ReadLoop ¶
func (c *Conn) ReadLoop()
ReadLoop 循环读取消息. 如果复用了HTTP Server, 建议开启goroutine, 阻塞会导致请求上下文无法被GC. Read messages in a loop. If HTTP Server is reused, it is recommended to enable goroutine, as blocking will prevent the context from being GC.
func (*Conn) ReadMessage ¶
func (*Conn) RemoteAddr ¶
RemoteAddr 返回远程网络地址 Returns the remote network address
func (*Conn) Session ¶
func (c *Conn) Session() SessionStorage
Session 获取会话存储 Gets the session storage
func (*Conn) SetDeadline ¶
SetDeadline 设置连接的截止时间 Sets the deadline for the connection
func (*Conn) SetNoDelay ¶
SetNoDelay 设置无延迟 控制操作系统是否应该延迟数据包传输以期望发送更少的数据包(Nagle算法). 默认值是 true(无延迟),这意味着数据在 Write 之后尽快发送. Controls whether the operating system should delay packet transmission in hopes of sending fewer packets (Nagle's algorithm). The default is true (no delay), meaning that data is sent as soon as possible after a Write.
func (*Conn) SetReadDeadline ¶
SetReadDeadline 设置读取操作的截止时间 Sets the deadline for read operations
func (*Conn) SetWriteDeadline ¶
SetWriteDeadline 设置写入操作的截止时间 Sets the deadline for write operations
func (*Conn) SubProtocol ¶
SubProtocol 获取协商的子协议 Gets the negotiated sub-protocol
func (*Conn) UpdateHandler ¶
func (c *Conn) UpdateHandler(handler EventHandler)
func (*Conn) WriteAsync ¶
WriteAsync 异步写 Writes messages asynchronously 异步非阻塞地将消息写入到任务队列, 收到回调后才允许回收payload内存 Write messages to the task queue asynchronously and non-blockingly, allowing payload memory to be recycled only after receiving the callback
func (*Conn) WriteClose ¶
WriteClose 发送关闭帧并断开连接 没有特殊需求的话, 推荐code=1000, reason=nil Send shutdown frame, active disconnection If you don't have any special needs, we recommend code=1000, reason=nil https://developer.mozilla.org/zh-CN/docs/Web/API/CloseEvent#status_codes
func (*Conn) WriteMessage ¶
WriteMessage 写入文本/二进制消息, 文本消息应该使用UTF8编码 Writes text/binary messages, text messages should be encoded in UTF8.
func (*Conn) WritePing ¶
WritePing 写入Ping消息, 携带的信息不要超过125字节 Control frame length cannot exceed 125 bytes
func (*Conn) WritePong ¶
WritePong 写入Pong消息, 携带的信息不要超过125字节 Control frame length cannot exceed 125 bytes
func (*Conn) WriteString ¶
WriteString 写入文本消息, 使用UTF8编码. Write text messages, should be encoded in UTF8.
type Dialer ¶
type Dialer interface {
// Dial 连接到指定网络上的地址
// Connects to the address on the named network
Dial(network, addr string) (c net.Conn, err error)
}
Dialer 拨号器接口 Dialer interface
type EventHandler ¶
type EventHandler interface {
// OnOpen 建立连接事件
// WebSocket connection was successfully established
OnOpen(socket *Conn)
// OnClose 关闭事件
// 接收到了网络连接另一端发送的关闭帧, 或者IO过程中出现错误主动断开连接
// 如果是前者, err可以断言为*CloseError
// Received a close frame from the other end of the network connection, or disconnected voluntarily due to an error in the IO process
// In the former case, err can be asserted as *CloseError
OnClose(socket *Conn, err error)
// OnPing 心跳探测事件
// Received a ping frame
OnPing(socket *Conn, payload []byte)
// OnPong 心跳响应事件
// Received a pong frame
OnPong(socket *Conn, payload []byte)
// OnMessage 消息事件
// 如果开启了ParallelEnabled, 会并行地调用OnMessage; 没有做recover处理.
// If ParallelEnabled is enabled, OnMessage is called in parallel. No recover is done.
OnMessage(socket *Conn, message *Message)
}
type Logger ¶
type Logger interface {
// Error 打印错误日志
// Printing the error log
Error(v ...any)
}
Logger 日志接口 Logger interface
type Map ¶
type Map[K comparable, V any] struct { sync.Mutex // contains filtered or unexported fields }
Map 线程安全的泛型映射类型. thread-safe generic map type.
func NewMap ¶
func NewMap[K comparable, V any](size ...int) *Map[K, V]
NewMap 创建一个新的 Map 实例 creates a new instance of Map size 参数用于指定初始容量,如果未提供则默认为 0 The size parameter is used to specify the initial capacity, defaulting to 0 if not provided.
func (*Map[K, V]) Delete ¶
func (c *Map[K, V]) Delete(key K)
Delete 从 Map 中删除指定键的值. deletes the value for the specified key from the Map.
func (*Map[K, V]) Load ¶
Load 从 Map 中加载指定键的值. Load loads the value for the specified key from the Map.
type Message ¶
type Message struct {
// content of the message
Data *bytes.Buffer
// opcode of the message
Opcode Opcode
}
type Server ¶
type Server struct {
// 错误处理回调函数
// Error handling callback function
OnError func(conn net.Conn, err error)
// 请求处理回调函数
// Request handling callback function
OnRequest func(conn net.Conn, br *bufio.Reader, r *http.Request)
// contains filtered or unexported fields
}
Server WebSocket服务器 Websocket server
func NewServer ¶
func NewServer(eventHandler EventHandler, option *ServerOption) *Server
NewServer 创建一个新的 WebSocket 服务器实例 Creates a new WebSocket server instance
func (*Server) GetUpgrader ¶
GetUpgrader 获取服务器的升级器实例 Retrieves the upgrader instance of the server
func (*Server) Run ¶
Run 启动 WebSocket 服务器,监听指定地址 Starts the WebSocket server and listens on the specified address
func (*Server) RunListener ¶
RunListener 使用指定的监听器运行 WebSocket 服务器 Runs the WebSocket server using the specified listener
type ServerOption ¶
type ServerOption struct {
// Logger
Logger Logger
// Create session storage space for custom SessionStorage implementations
NewSession func() SessionStorage
// Authentication function for connection establishment requests
Authorize func(r *http.Request, session SessionStorage) bool
// Additional response headers (may not be supported by the client)
// https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3
ResponseHeader http.Header
// TLS configuration
TlsConfig *tls.Config
// Recovery function
Recovery func(logger Logger)
// WebSocket sub-protocol, handshake failure disconnects the connection
SubProtocols []string
// Handshake timeout duration
HandshakeTimeout time.Duration
// Maximum payload size for writing
WriteMaxPayloadSize int
// Read buffer size
ReadBufferSize int
// Maximum payload size for reading
ReadMaxPayloadSize int
// Parallel goroutine limit
ParallelGolimit int
// Whether UTF-8 check is enabled
CheckUtf8Enabled bool
// Whether parallel processing is enabled
ParallelEnabled bool
// contains filtered or unexported fields
}
ServerOption 服务端配置 Server configurations
type SessionStorage ¶
type SessionStorage interface {
// Len 返回存储中的键值对数量
// Returns the number of key-value pairs in the storage
Len() int
// Load 根据键获取值,如果键存在则返回值和 true,否则返回 nil 和 false
// retrieves the value for a given key. If the key exists, it returns the value and true; otherwise, it returns nil and false
Load(key string) (value any, exist bool)
// Delete 根据键删除存储中的键值对
// removes the key-value pair from the storage for a given key
Delete(key string)
// Store 存储键值对
// saves the key-value pair in the storage
Store(key string, value any)
// Range 遍历
// 如果函数返回 false,遍历将提前终止.
// If the function returns false, the iteration stops early.
Range(f func(key string, value any) bool)
}
SessionStorage 会话存储
type Upgrader ¶
type Upgrader struct {
// contains filtered or unexported fields
}
func NewUpgrader ¶
func NewUpgrader(eventHandler EventHandler, option *ServerOption) *Upgrader
NewUpgrader 创建一个新的 Upgrader 实例 Creates a new instance of Upgrader
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
autobahn/client
command
|
|
|
autobahn/server
command
|
|
|
chatroom
command
|
|
|
client
command
|
|
|
echo
command
|
|
|
push
command
|
|
|
wss
command
|
|