Documentation
¶
Overview ¶
Package uws provides an asynchronous WebSocket server built on UIO.
Index ¶
- Constants
- Variables
- type CloseEvent
- type Conn
- func (c *Conn) BeginMessage(typ MessageType) (*Writer, error)
- func (c *Conn) Close(code uint16, reason string) error
- func (c *Conn) IsClosed() bool
- func (c *Conn) LocalAddr() net.Addr
- func (c *Conn) Ping(payload []byte) error
- func (c *Conn) RemoteAddr() net.Addr
- func (c *Conn) Request() *http.Request
- func (c *Conn) SendBinary(payload []byte) error
- func (c *Conn) SendText(payload []byte) error
- func (c *Conn) SetDeadline(deadline time.Time) error
- func (c *Conn) SetNoDelay(noDelay bool) error
- func (c *Conn) SetReadDeadline(deadline time.Time) error
- func (c *Conn) SetUserdata(value any)
- func (c *Conn) SetWriteDeadline(deadline time.Time) error
- func (c *Conn) Subprotocol() string
- func (c *Conn) Userdata() any
- type Dialer
- type Executor
- type Handler
- type Message
- type MessageType
- type Server
- type Writer
Constants ¶
const ( // DefaultMaxHeaderBytes is the default HTTP upgrade header limit. DefaultMaxHeaderBytes = handshake.DefaultMaxBytes // DefaultMaxFramePayload is the default wire payload limit for one frame. DefaultMaxFramePayload = 16 << 20 // DefaultMaxMessageSize is the default decompressed message size limit. DefaultMaxMessageSize = 64 << 20 // DefaultMaxOutboundBytes is the default accepted but unsent wire byte // limit. It includes room for the largest legal frame header so a maximum // sized default frame is not rejected before reaching the transport. DefaultMaxOutboundBytes = DefaultMaxFramePayload + 14 // DefaultCloseTimeout is the default graceful close handshake timeout. DefaultCloseTimeout = 5 * time.Second // DefaultHandshakeTimeout is the default HTTP upgrade timeout. DefaultHandshakeTimeout = 10 * time.Second )
Variables ¶
var ( // ErrClosed reports an operation on a closed connection. ErrClosed = errors.New("uws: connection closed") // ErrNotReady reports an operation attempted before the handshake completes. ErrNotReady = errors.New("uws: handshake not complete") // ErrBackpressure reports that the transport outbound queue is full. ErrBackpressure = errors.New("uws: outbound queue is full") // ErrApplicationBackpressure reports that the Executor mailbox is full. ErrApplicationBackpressure = errors.New("uws: application queue is full") // ErrExecutorRejected reports that Executor.Submit rejected a callback. ErrExecutorRejected = errors.New("uws: executor rejected callback") // ErrWriterClosed reports an operation on a closed message writer. ErrWriterClosed = errors.New("uws: message writer is closed") // ErrServerStarted reports a second attempt to run a Server listener after // its transport has already started. ErrServerStarted = errors.New("uws: server already started") // ErrProtocol reports a WebSocket protocol violation. ErrProtocol = frame.ErrProtocol )
Functions ¶
This section is empty.
Types ¶
type CloseEvent ¶ added in v1.1.0
type CloseEvent struct {
// Code is the peer or locally generated WebSocket close status code.
Code uint16
// Reason is the optional close reason sent with Code.
Reason string
// Err is the transport, protocol, or application error that caused closure.
Err error
}
CloseEvent describes why a WebSocket connection closed.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn is an established or handshaking WebSocket connection.
func (*Conn) BeginMessage ¶
func (c *Conn) BeginMessage(typ MessageType) (*Writer, error)
BeginMessage starts a fragmented message and holds the connection's write ownership until Writer.Close returns. It is non-blocking with respect to the socket; callers must close a successful writer. A Write error aborts the connection and releases write ownership immediately. With compression enabled, writes are compressed incrementally and emitted as continuation frames, so large messages do not need a second full plaintext buffer.
func (*Conn) RemoteAddr ¶
RemoteAddr returns the peer transport address.
func (*Conn) Request ¶ added in v1.1.0
Request returns the HTTP upgrade request until OnOpen returns for a connection adopted through Server.ServeHTTP. It returns nil afterward and for connections accepted by Server.Serve. The request is read-only.
func (*Conn) SendBinary ¶
SendBinary queues payload as one binary message. The transport flushes accepted data at its callback or task boundary.
func (*Conn) SendText ¶
SendText queues payload as one text message. The transport flushes accepted data at its callback or task boundary.
func (*Conn) SetDeadline ¶ added in v1.1.0
SetDeadline forwards the transport read and write deadline. A zero value clears it.
func (*Conn) SetNoDelay ¶ added in v1.1.0
SetNoDelay controls whether the underlying TCP connection uses Nagle's algorithm.
func (*Conn) SetReadDeadline ¶ added in v1.1.0
SetReadDeadline forwards the transport read deadline. A zero value clears it.
func (*Conn) SetUserdata ¶ added in v1.1.0
SetUserdata replaces the user data associated with the connection. It is not safe for concurrent use from multiple goroutines.
func (*Conn) SetWriteDeadline ¶ added in v1.1.0
SetWriteDeadline forwards the transport write deadline. A zero value clears it.
func (*Conn) Subprotocol ¶
Subprotocol returns the negotiated WebSocket subprotocol, or an empty string.
type Dialer ¶
type Dialer struct {
// Events configures the underlying UIO transport. Nil uses a default Events.
Events *uio.Events
// Subprotocols lists protocols offered in preference order.
Subprotocols []string
// MaxHeaderBytes bounds the HTTP upgrade response header. Zero uses the default.
MaxHeaderBytes int
// MaxFramePayload bounds each wire frame payload. On reads, it also bounds
// aggregate compressed payload across a fragmented message.
MaxFramePayload uint64
// MaxMessageSize bounds a complete message after decompression.
MaxMessageSize uint64
// MaxOutboundBytes bounds accepted but unsent wire bytes per connection.
// Zero uses DefaultMaxOutboundBytes; a negative value disables this limit.
MaxOutboundBytes int
// EnableCompression offers RFC 7692 permessage-deflate.
EnableCompression bool
// CompressionLevel selects the flate level. Zero uses default compression.
CompressionLevel int
// DisableUTF8Check skips Text Message UTF-8 validation. This violates RFC
// 6455 and should only be used with trusted peers. Close reasons remain validated.
DisableUTF8Check bool
// CloseTimeout bounds the graceful WebSocket close handshake. A zero value
// uses DefaultCloseTimeout.
CloseTimeout time.Duration
// HandshakeTimeout bounds the HTTP upgrade handshake. A zero value uses
// DefaultHandshakeTimeout.
HandshakeTimeout time.Duration
// Executor dispatches OnOpen, OnMessage, and OnClose callbacks away from
// the I/O event loop. A nil executor preserves synchronous callbacks. If
// Submit rejects, remaining callbacks are dropped rather than run on the loop.
Executor Executor
// contains filtered or unexported fields
}
Dialer creates outbound WebSocket connections over a shared UIO transport. Configure its fields before the first Dial; the first Dial freezes the connection configuration.
func NewDialer ¶
func NewDialer() *Dialer
NewDialer returns a Dialer configured with default transport settings.
func (*Dialer) Close ¶
Close permanently stops the dialer, cancels in-flight connection attempts, and requests closure of established connections. Subsequent Dial calls return the first close cause. OnClose reports connection completion unless the configured Executor rejects dispatch.
func (*Dialer) Dial ¶
Dial starts a WebSocket connection. The supplied context bounds the TCP connection and WebSocket handshake; it no longer affects the connection after OnOpen. The returned connection remains pending until Handler.OnOpen reports handshake success or Handler.OnClose reports a handshake failure. The returned error only covers failures that prevent the connection attempt from starting.
type Executor ¶
type Executor interface {
// Submit schedules callback and reports whether it was accepted.
Submit(func()) bool
}
Executor runs application callbacks outside the I/O event loop. Submit must return promptly and reports false when a bounded worker queue is full.
type Handler ¶
type Handler interface {
// OnOpen is called after a successful WebSocket handshake.
OnOpen(*Conn)
// OnMessage receives complete messages in wire order.
OnMessage(*Conn, Message)
// OnClose is called once after the transport closes. A client handshake
// failure may call it without a preceding OnOpen. If Executor rejects
// dispatch, pending callbacks, including OnClose, may be dropped.
OnClose(*Conn, CloseEvent)
}
Handler receives ordered lifecycle and message callbacks for a connection.
type Message ¶
type Message struct {
// Type identifies whether Payload contains text or binary data.
Type MessageType
// Payload is valid until OnMessage returns. Call Clone before retaining it
// or handing it to another goroutine.
Payload []byte
}
Message is one complete text or binary WebSocket message.
type MessageType ¶
type MessageType uint8
MessageType identifies the payload format of a WebSocket message.
const ( // TextMessage identifies a UTF-8 text message. TextMessage MessageType = 1 // BinaryMessage identifies a binary message. BinaryMessage MessageType = 2 )
type Server ¶
type Server struct {
// Events configures the underlying UIO transport. Nil uses a default Events.
Events *uio.Events
// Handler receives connection lifecycle and message callbacks. It may be nil.
Handler Handler
// CheckOrigin accepts an upgrade request. Nil accepts every origin.
CheckOrigin func(*http.Request) bool
// Subprotocols lists supported protocols in server preference order.
Subprotocols []string
// MaxHeaderBytes bounds HTTP upgrade headers read by the native Serve path.
// When using ServeHTTP, configure http.Server.MaxHeaderBytes instead.
MaxHeaderBytes int
// MaxFramePayload bounds each wire frame payload. On reads, it also bounds
// aggregate compressed payload across a fragmented message.
MaxFramePayload uint64
// MaxMessageSize bounds a complete message after decompression.
MaxMessageSize uint64
// MaxOutboundBytes bounds accepted but unsent wire bytes per connection.
// Zero uses DefaultMaxOutboundBytes; a negative value disables this limit.
MaxOutboundBytes int
// EnableCompression enables RFC 7692 permessage-deflate negotiation.
EnableCompression bool
// CompressionLevel selects the flate level. Zero uses default compression.
CompressionLevel int
// DisableUTF8Check skips Text Message UTF-8 validation. This violates RFC
// 6455 and should only be used with trusted peers. Close reasons remain validated.
DisableUTF8Check bool
// CloseTimeout bounds the graceful WebSocket close handshake. A zero value
// uses DefaultCloseTimeout.
CloseTimeout time.Duration
// HandshakeTimeout bounds the HTTP upgrade handshake. A zero value uses
// DefaultHandshakeTimeout.
HandshakeTimeout time.Duration
// Executor dispatches OnOpen, OnMessage, and OnClose callbacks away from
// the I/O event loop. A nil executor preserves synchronous callbacks. If
// Submit rejects, remaining callbacks are dropped rather than run on the loop.
Executor Executor
// AllowCompressionContextTakeover enables RFC 7692 context takeover for
// peers that do not request a no-context-takeover parameter. It is disabled
// by default to bound per-connection compression state.
AllowCompressionContextTakeover bool
// HeartbeatInterval enables server pings when positive.
HeartbeatInterval time.Duration
// HeartbeatTimeout closes a connection without a pong. Zero uses twice the interval.
HeartbeatTimeout time.Duration
// contains filtered or unexported fields
}
Server accepts WebSocket connections over a UIO transport. Configure its fields before calling Serve; Serve freezes the connection configuration.
func (*Server) Close ¶
Close permanently stops the server and requests transport shutdown. Serve returns after all event loops and callbacks have exited.
func (*Server) Serve ¶
Serve starts the event loops and optionally listens on one address. Calling Serve without an address prepares the Server for use as an http.Handler.
func (*Server) ServeHTTP ¶ added in v1.1.0
func (s *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request)
ServeHTTP upgrades a plain HTTP/1.1 TCP connection and transfers it from net/http to the Server's UIO event loops. Serve must already be running. TLS and HTTP/2 are not supported.