Documentation
¶
Overview ¶
Package uws provides an asynchronous WebSocket server and client built on UIO.
Index ¶
- Constants
- Variables
- func ClientLayer(opts LayerOptions) uio.Layer
- func ServerLayer(opts LayerOptions) uio.Layer
- type BlockingConn
- func (c *BlockingConn) Close(code uint16, reason string) error
- func (c *BlockingConn) CloseEventInfo() CloseEvent
- func (c *BlockingConn) Flush(ctx context.Context) error
- func (c *BlockingConn) InboundBytes() int
- func (c *BlockingConn) InboundMessages() int
- func (c *BlockingConn) ReadMessage(ctx context.Context) (Message, error)
- func (c *BlockingConn) ReadMessageInto(ctx context.Context, dst []byte) (MessageType, []byte, error)
- func (c *BlockingConn) WriteBinary(ctx context.Context, payload []byte) error
- func (c *BlockingConn) WriteMessage(ctx context.Context, typ MessageType, payload []byte) error
- func (c *BlockingConn) WritePrepared(ctx context.Context, m *PreparedMessage) error
- func (c *BlockingConn) WriteText(ctx context.Context, text string) error
- type BlockingOption
- type Client
- type CloseError
- type CloseEvent
- type Conn
- func (c *Conn) Close(code uint16, reason string) error
- func (c *Conn) IsClosed() bool
- func (c *Conn) LocalAddr() net.Addr
- func (c *Conn) OutboundBuffered() int
- func (c *Conn) PauseRead() error
- func (c *Conn) Ping(payload []byte) error
- func (c *Conn) ReadPaused() bool
- func (c *Conn) RemoteAddr() net.Addr
- func (c *Conn) Request() *http.Request
- func (c *Conn) ResumeRead() error
- func (c *Conn) Send(typ MessageType, payload []byte) error
- func (c *Conn) SendBinary(payload []byte) error
- func (c *Conn) SendPrepared(m *PreparedMessage) error
- func (c *Conn) SendText(payload string) 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) TLSState() (tls.ConnectionState, bool)
- func (c *Conn) Userdata() any
- type Dialer
- type Handler
- type HandshakeError
- type LayerOptions
- type Message
- type MessageType
- type Options
- type PreparedMessage
- type RejectError
- type Server
- type Stats
- type TrafficObserver
Constants ¶
const ( // DefaultBlockingQueueMessages bounds queued inbound messages before reads // pause on the underlying transport. DefaultBlockingQueueMessages = 64 // DefaultBlockingQueueBytes is the default byte budget (64 KiB) for // inbound message queuing and soft outbound write backpressure. DefaultBlockingQueueBytes = uio.DefaultBlockingBuffer )
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 // DefaultCloseTimeout is the default graceful close handshake timeout. DefaultCloseTimeout = 5 * time.Second // DefaultHandshakeTimeout is the default HTTP upgrade timeout. DefaultHandshakeTimeout = 10 * time.Second )
const DefaultMaxInboundBuffered = 64 << 10
DefaultMaxInboundBuffered is the default transport receive bound, so an explicit Conn.PauseRead stops socket reads once buffered input reaches it.
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 a send MaxOutboundBuffered has no room for: // the queue is full, or the frame or message is larger than the limit // itself, which the queue's emptiness cannot fix. ErrBackpressure = errors.New("uws: outbound queue is full") // 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 )
var DefaultDialer = &Dialer{}
DefaultDialer is the Dialer the package-level Dial uses. It runs with the default options and lives until the process ends, like http.DefaultClient; close it and every connection it made by calling DefaultDialer.Close.
var ErrBlockingOnTurn = uio.ErrBlockingOnTurn
ErrBlockingOnTurn reports an attempt to invoke a blocking operation on a connection turn or event-loop goroutine.
var ErrInvalidOptions = errors.New("uws: invalid options")
ErrInvalidOptions reports Options a server or dialer cannot run with.
Functions ¶
func ClientLayer ¶ added in v1.8.0
func ClientLayer(opts LayerOptions) uio.Layer
ClientLayer runs the client side of the WebSocket protocol as a uio.Layer: it sends the upgrade request for Target, a ws:// or wss:// URL whose host and path the request names, and opens the layers above once the server accepted it. A dial through it returns once the handshake succeeded, and reports a refusal or a failure as its error — a *HandshakeError when the server answered. The scheme names no transport: TLS under the layer is another layer's, installed below it. One layer dials one target. See ServerLayer for the byte stream the layer carries and for invalid options.
func ServerLayer ¶ added in v1.8.0
func ServerLayer(opts LayerOptions) uio.Layer
ServerLayer runs the server side of the WebSocket protocol as a uio.Layer, for a stack of your own:
listener, err := events.Listen(addr, uio.WithLayers(tls, uws.ServerLayer(opts), tunnel))
It answers the upgrade request, and opens the layers above once the handshake succeeded; a request it refuses gets its answer and closes the connection — the layers above never see OnOpen, and end with OnClose alone. From then on it carries a byte stream: what the layer above writes leaves as Binary messages — split at MaxMessageSize — and the payload of every message that arrives, Text or Binary, is handed up once the message is whole, message boundaries dropped. Pings are answered, heartbeats run, and a Close from the peer is answered and ends the connection. Closing the connection from above sends a Close frame first: 1000 for a graceful close, 1011 for an abort — an abort sends it best-effort, since nothing is flushed or drained. The stream has no half-close: CloseWrite is not supported.
Each write from above leaves as its own frame, through the Events the layer runs on: set its WriteBufferedThreshold for the writes a Handler makes in one callback to leave in one send, as a Server's do.
Options that are not valid for a layer fail every connection through it with ErrInvalidOptions — a dial reports it — as LayerOptions.Validate does.
The layer above can read the negotiated subprotocol — and what Authorize returned for this connection — through uio.FindLayer:
if ws, ok := uio.FindLayer[interface{ Userdata() any }](conn); ok { … }
if ws, ok := uio.FindLayer[interface{ Subprotocol() string }](conn); ok { … }
Types ¶
type BlockingConn ¶ added in v1.9.0
type BlockingConn struct {
*Conn
// contains filtered or unexported fields
}
BlockingConn is a synchronous, message-oriented WebSocket endpoint usable on both client connections (via Dial / Dialer.DialClient) and upgraded server connections (via NewBlockingConn in OnOpen or OnMessage).
Inbound backpressure pauses the underlying transport via Conn.PauseRead without ever blocking connection turn workers, so heartbeats, transport deadlines, and shutdowns continue to run natively on the event loop.
func NewBlockingConn ¶ added in v1.9.0
func NewBlockingConn(conn *Conn, opts ...BlockingOption) (*BlockingConn, error)
NewBlockingConn switches an open *Conn (such as a server connection inside OnOpen or OnMessage) from push OnMessage callbacks to synchronous pull/push BlockingConn operations. Calling NewBlockingConn again on the same *Conn returns the existing *BlockingConn.
When upgrading an already-open push *Conn, call NewBlockingConn inside OnOpen or OnMessage so the handler handoff is serialized with frame delivery.
func (*BlockingConn) Close ¶ added in v1.9.0
func (c *BlockingConn) Close(code uint16, reason string) error
Close validates code and reason, stops further inbound message intake (while preserving already-queued messages for subsequent ReadMessage calls), and initiates the WebSocket Close handshake.
func (*BlockingConn) CloseEventInfo ¶ added in v1.9.0
func (c *BlockingConn) CloseEventInfo() CloseEvent
CloseEventInfo reports how the connection ended once closed.
func (*BlockingConn) Flush ¶ added in v1.9.0
func (c *BlockingConn) Flush(ctx context.Context) error
Flush flushes queued outbound frames and blocks until the outbound buffer drains, the connection closes, or ctx ends.
func (*BlockingConn) InboundBytes ¶ added in v1.9.0
func (c *BlockingConn) InboundBytes() int
InboundBytes reports the total payload bytes of unread messages currently queued.
func (*BlockingConn) InboundMessages ¶ added in v1.9.0
func (c *BlockingConn) InboundMessages() int
InboundMessages reports the number of unread messages currently queued.
func (*BlockingConn) ReadMessage ¶ added in v1.9.0
func (c *BlockingConn) ReadMessage(ctx context.Context) (Message, error)
ReadMessage returns the next received WebSocket message, blocking until one arrives, the connection closes, or ctx ends. A canceled or timed-out ctx returns ctx.Err() without closing the connection.
func (*BlockingConn) ReadMessageInto ¶ added in v1.9.0
func (c *BlockingConn) ReadMessageInto(ctx context.Context, dst []byte) (MessageType, []byte, error)
ReadMessageInto appends the next received message's payload into dst[:0] (reusing dst's backing array when large enough for zero heap allocations) and returns the message type and populated slice.
func (*BlockingConn) WriteBinary ¶ added in v1.9.0
func (c *BlockingConn) WriteBinary(ctx context.Context, payload []byte) error
WriteBinary sends a binary WebSocket message, suspending when the outbound buffer is full until space drains, the connection closes, or ctx ends.
func (*BlockingConn) WriteMessage ¶ added in v1.9.0
func (c *BlockingConn) WriteMessage(ctx context.Context, typ MessageType, payload []byte) error
WriteMessage sends one message of typ, suspending on outbound backpressure until space drains, the connection closes, or ctx ends.
func (*BlockingConn) WritePrepared ¶ added in v1.9.0
func (c *BlockingConn) WritePrepared(ctx context.Context, m *PreparedMessage) error
WritePrepared sends m on a blocking connection, suspending while the outbound buffer is full until space drains, the connection closes, or ctx ends.
type BlockingOption ¶ added in v1.9.0
type BlockingOption interface {
// contains filtered or unexported methods
}
BlockingOption configures a BlockingConn (or Client).
func WithReadQueueBytes ¶ added in v1.9.0
func WithReadQueueBytes(bytes int) BlockingOption
WithReadQueueBytes sets the inbound byte watermark at which BlockingConn pauses reading from the underlying transport.
func WithReadQueueMessages ¶ added in v1.9.0
func WithReadQueueMessages(count int) BlockingOption
WithReadQueueMessages sets the maximum number of queued inbound messages before BlockingConn pauses reading from the underlying transport.
func WithWriteBuffer ¶ added in v1.9.0
func WithWriteBuffer(bytes int) BlockingOption
WithWriteBuffer sets the soft outbound byte window for BlockingConn's blocking WriteMessage / WriteText / WriteBinary methods.
type Client ¶ added in v1.8.0
type Client = BlockingConn
Client is a type alias for BlockingConn, preserving full backward compatibility for Dial and Dialer.DialClient callers.
type CloseError ¶ added in v1.8.0
type CloseError struct {
CloseEvent
}
CloseError reports how a BlockingConn's connection ended. ReadMessage and ReadMessageInto return it after the connection closed and every queued message was returned.
func (*CloseError) Error ¶ added in v1.8.0
func (e *CloseError) Error() string
func (*CloseError) Unwrap ¶ added in v1.8.0
func (e *CloseError) Unwrap() error
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. UIO serializes protocol and handler callbacks per connection; atomics here coordinate external writers, timers, heartbeat scanning, and transport callbacks. The fields every message touches come first, so they share as few cache lines as the struct's size class allows.
func (*Conn) Close ¶
Close starts a graceful WebSocket close handshake. The Close frame follows every message accepted before it. When the outbound limit has no room for the frame, it waits for the transport to drain instead of failing; either way the connection stops accepting messages, and one that arrives already received but not yet reported to the Handler is dropped rather than delivered. CloseTimeout bounds the handshake, which the connection carries on after Close returns.
func (*Conn) OutboundBuffered ¶ added in v1.9.0
OutboundBuffered returns accepted bytes still waiting in this connection's WebSocket write batch and the transport below it. It includes frame headers and, over TLS or other layers, what those layers hold and add. Bytes already written to the socket's kernel buffer are not included.
This is a concurrent observation, not a write reservation: a handoff can briefly count bytes in both the batch and transport. MaxOutboundBuffered remains the hard admission limit. The method takes no write lock and is safe from any goroutine, including TrafficObserver.OnBytesWritten. An unattached connection reports zero.
func (*Conn) PauseRead ¶ added in v1.9.0
PauseRead stops consuming incoming WebSocket frames until ResumeRead. It is safe from any goroutine and from OnOpen or OnMessage. A callback already in progress may finish; a pause made by OnMessage takes effect before the next frame, including frames buffered in the same socket read. The frames wait in the transport, which stops reading a plain socket at once and keeps the end of the stream behind them: a peer that sends and then closes its side is answered after ResumeRead, so a paused connection whose peer left lingers until then, or until a heartbeat or read deadline ends it. Writes and timers continue normally. This also works over TLS.
Pausing delays control frames too, including Ping and Pong. Heartbeat and close deadlines still run; starting a local Close overrides the pause so the close handshake can finish. Calls are idempotent, not reference counted: callers sharing this switch must coordinate their ownership. The connection must have opened and must not be closing or closed.
func (*Conn) ReadPaused ¶ added in v1.9.0
ReadPaused reports whether PauseRead currently holds incoming WebSocket frames.
func (*Conn) RemoteAddr ¶
RemoteAddr returns the peer transport address.
func (*Conn) Request ¶ added in v1.1.0
Request returns the HTTP upgrade request during OnOpen for server connections, whether accepted by Server.Serve or adopted through Server.ServeHTTP. It returns nil afterward — handlers that need it beyond OnOpen must keep it — and for client connections. The request is read-only.
func (*Conn) ResumeRead ¶ added in v1.9.0
ResumeRead clears the pause requested by PauseRead and schedules a read turn, so already buffered frames need no new network input to be delivered. Without that pause it does nothing. It is safe from any goroutine, including TrafficObserver.OnBytesWritten, and is idempotent. The connection must have opened and must not be closing or closed.
func (*Conn) Send ¶ added in v1.8.0
func (c *Conn) Send(typ MessageType, payload []byte) error
Send queues payload as one message of typ — TextMessage or BinaryMessage — framing it with that opcode. It is SendText and SendBinary under one name for a caller that holds bytes and a type already: text goes out without converting the bytes to a string first. An unknown typ reports ErrProtocol.
As with SendText and SendBinary, payload is framed without being retained: the bytes may be reused once Send returns. A text payload must be valid UTF-8; it is sent as given, and only received text is validated.
func (*Conn) SendBinary ¶
SendBinary queues payload as one binary message. The transport flushes accepted data in the connection's current or next I/O task.
func (*Conn) SendPrepared ¶ added in v1.9.0
func (c *Conn) SendPrepared(m *PreparedMessage) error
SendPrepared queues m to c without copying payload bytes on compatible server connections, and transparently falls back to per-connection framing when client masking, stateful compression dictionaries, or frame splitting apply.
func (*Conn) SendText ¶
SendText queues payload as one text message. The transport flushes accepted data in the connection's current or next I/O task. payload must be valid UTF-8: it is sent as given, and only received text is validated.
payload's bytes are framed without a copy: a string converts to the transaction's view of the wire for free, and nothing on the send path writes through it.
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.
func (*Conn) TLSState ¶ added in v1.8.0
func (c *Conn) TLSState() (tls.ConnectionState, bool)
TLSState reports the TLS connection state of a connection that runs over TLS — a wss one, or one whose stack has a TLS layer below the WebSocket protocol: what the handshake settled on, the server name the client asked for, the client's certificates.
type Dialer ¶
type Dialer struct {
// Options configures the protocol, the transport and backpressure.
Options
// Header is added to every upgrade request, for credentials such as an
// Authorization token. The headers the handshake sets itself are refused
// — Host, Upgrade, Connection, Content-Length, Transfer-Encoding, Expect,
// and Sec-WebSocket-Key, -Version, -Protocol, -Extensions and -Accept —
// the first Dial returns ErrInvalidOptions.
Header http.Header
// RequestHeader, when set, returns headers for one dial, given its
// userdata — nil for a DialClient, which dials without one; they replace
// Header's values of the same name. A header the handshake sets itself
// fails that Dial with ErrInvalidOptions.
RequestHeader func(userdata any) http.Header
// 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 (*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.
func (*Dialer) Dial ¶
Dial starts a WebSocket connection and returns once the upgrade request is on its way — with a TLSConfig, once the transport's stack opened, which is where the request is written from; the Handler reports the rest. An error means no connection was made and no callback follows — uio.ErrFirstTurnRefused when a custom Executor declined the connection's first turn. After a nil error, OnOpen reports a completed handshake, and OnClose always reports how the connection ended, a failed handshake or upgrade request included. userdata is the connection's Userdata in every callback. ctx bounds the TCP connection and the handshake, not the connection after OnOpen.
func (*Dialer) DialClient ¶ added in v1.8.0
func (d *Dialer) DialClient(ctx context.Context, addr string, opts ...BlockingOption) (*Client, error)
DialClient connects and returns the synchronous Client (*BlockingConn) once the WebSocket handshake completes. Options.Handler must be nil.
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 is released. A client
// handshake failure may call it without a preceding OnOpen. The socket
// itself may close shortly after; see uio.Handler's OnClose.
OnClose(*Conn, CloseEvent)
}
Handler receives ordered lifecycle and message callbacks for a connection.
type HandshakeError ¶ added in v1.8.0
type HandshakeError struct {
StatusCode int
Header http.Header
// Reason is the response body, when the server sent a short one; a uws
// server sends RejectError.Reason there.
Reason string
}
HandshakeError reports a server that refused the upgrade: it answered with a status other than 101. A Dialer's OnClose gets it as CloseEvent.Err, and DialClient returns it, wrapped in a CloseError, so errors.As finds it.
func (*HandshakeError) Error ¶ added in v1.8.0
func (e *HandshakeError) Error() string
type LayerOptions ¶ added in v1.8.0
type LayerOptions struct {
// Options holds the protocol's settings: subprotocols, limits,
// compression, timeouts, and heartbeats; ReadBufferSize and WriteCoalesce
// size only the layer's write batches and read rounds, as the socket's
// reads are its Events'. The transport's own — Handler, Pollers, ReusePort,
// Executor, TLSConfig, MaxInboundBuffered and MaxOutboundBuffered — belong
// to the Events the layer is installed on and must be left zero: a stack's
// TLS is a layer of its own, and its buffer limits belong to Events.
// Pace at the layer above when needed, as ubridge.Bridge does by leaving
// bytes unread.
Options
// CheckOrigin and Authorize decide a ServerLayer's upgrade requests as
// they do a Server's; what Authorize returns is the layer's to report,
// through uio.FindLayer — see ServerLayer.
CheckOrigin func(*http.Request) bool
Authorize func(r *http.Request) (userdata any, err error)
// Header is added to a ClientLayer's upgrade request, as a Dialer's is.
Header http.Header
// Target is the ws:// or wss:// URL a ClientLayer's upgrade request
// names: the host and path the request carries. One layer dials one
// target; the transport address itself is the dial's, and the scheme
// names no transport — TLS under the layer is another layer's. A
// ServerLayer refuses it.
Target string
}
LayerOptions configures ServerLayer and ClientLayer.
func (LayerOptions) Validate ¶ added in v1.8.0
func (o LayerOptions) Validate() error
Validate reports what ServerLayer, and ClientLayer when Target is set, would refuse: the error every connection through the layer would fail with.
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.
func (Message) Bytes ¶ added in v1.8.0
Bytes returns Payload, the counterpart of Text for a binary message handed straight back to SendBinary. It is Payload itself, valid on the same terms: only until OnMessage returns unless cloned.
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 Options ¶ added in v1.8.0
type Options struct {
// Handler receives the connection callbacks of every connection the
// server or dialer makes. It may be nil, which leaves the protocol
// running without application callbacks; a Dialer whose Handler is set
// refuses DialClient, which installs its own.
Handler Handler
// Subprotocols lists supported protocols in server preference order,
// offered in the same order by a Dialer.
Subprotocols []string
// MaxHeaderBytes bounds the HTTP upgrade headers this end reads: the
// request on a server, the response on a dialer. Zero uses 32 KiB.
MaxHeaderBytes int
// MaxFramePayload bounds each wire frame payload. On reads, it also
// bounds aggregate compressed payload across a fragmented message. Zero
// uses 16 MiB.
MaxFramePayload uint64
// MaxMessageSize bounds a complete message after decompression. Zero uses
// 64 MiB.
MaxMessageSize uint64
// EnableCompression enables RFC 7692 permessage-deflate.
EnableCompression bool
// CompressionLevel selects the flate level, 1 through 9. Zero uses the
// library default level; there is no level 0: permessage-deflate with no
// compression only adds framing overhead.
CompressionLevel int
// KeepCompressionContext keeps this end's compression context between
// messages. Off by default: every message starts a fresh context and the
// negotiation asks for the same of the peer, which bounds per-connection
// compression state.
KeepCompressionContext bool
// 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
// HandshakeTimeout bounds the HTTP upgrade handshake. Zero uses 10s.
HandshakeTimeout time.Duration
// CloseTimeout bounds the graceful WebSocket close handshake. Zero uses
// 5s.
CloseTimeout time.Duration
// HeartbeatInterval makes this end ping its peer when positive. Zero
// disables heartbeats; both servers and dialers may enable them. The
// heartbeat runs in the connection's own turns, so a Handler callback
// that blocks also pauses its connection's heartbeat until it returns;
// a paused BlockingConn / Client never blocks turns, so its heartbeat
// timeout continues to run natively.
HeartbeatInterval time.Duration
// HeartbeatTimeout bounds both the time a ping may remain queued and the
// time to receive its matching pong after it is written. Zero uses twice
// HeartbeatInterval.
HeartbeatTimeout time.Duration
// Pollers is the number of event loops. Zero uses UIO's default.
Pollers int
// ReadBufferSize is the size of each socket read. Zero uses UIO's default
// of 4 KiB. It also sizes the write batch blocks the connection's replies
// are coalesced into, clamped to 4-64 KiB. With TLSConfig a record
// carries up to 16 KiB and a read smaller than that splits one record
// across several rounds; a wss server moving bulk data reads about twice
// as fast with 16 KiB and half again with 64 KiB.
ReadBufferSize int
// WriteCoalesce makes callback writes smaller than this value join the
// connection's outbound batch instead of attempting an immediate send.
// Zero uses 4 KiB; a negative value disables size-based buffering.
WriteCoalesce int
// ReusePort sets SO_REUSEPORT on listeners.
ReusePort bool
// Executor runs the connection and write turns; nil uses UIO's own
// scheduler.
Executor uio.Executor
// TLSConfig makes the connections wss. On a Server it holds the
// certificates, and every connection the Server accepts runs TLS under
// the WebSocket protocol; ServeHTTP still takes plain HTTP/1.1 upgrades
// only. Authorize sees the TLS state on its request's TLS field, and
// Conn.TLSState reports it. On a Dialer it is what wss:// dials verify
// the server with — an empty Config verifies against the system roots —
// and when it names no ServerName, each dial verifies the host its URL
// names; ws:// dials run without TLS. A Dialer without it refuses wss://.
// The TLS handshake runs before the WebSocket one, each bounded by
// HandshakeTimeout, and a dial that fails it reports its cause.
TLSConfig *tls.Config
// MaxInboundBuffered bounds unread input buffered in the transport, which
// lets an explicit Conn.PauseRead apply TCP backpressure to the peer. Zero
// uses DefaultMaxInboundBuffered (64 KiB); a negative value disables the
// explicit bound beyond UIO's pause floor.
MaxInboundBuffered int
// MaxOutboundBuffered bounds the bytes queued for one connection from any
// sender: a send that would pass it returns ErrBackpressure and queues
// nothing, so a slow peer cannot grow the queue without bound however the
// output is produced. Size it to fit the largest message sent. Zero means
// no limit.
MaxOutboundBuffered int
}
Options holds every setting a Server or Dialer accepts. The zero value means the defaults; the fields are documented with them. Server and Dialer share the type so the two ends cannot drift apart. A value is read when Serve or Dial first starts its transport and never again: changing the Options of a running Server or Dialer has no effect.
type PreparedMessage ¶ added in v1.9.0
type PreparedMessage struct {
// contains filtered or unexported fields
}
PreparedMessage holds an immutable, pre-framed WebSocket message backed by uio.SharedBuffer for zero-copy fan-out across server connections.
On standard server connections (uncompressed, or RFC 7692 permessage-deflate without context takeover), Conn.SendPrepared queues a read-only view of the pre-built wire frame directly to the transport without copying payload bytes or allocating per connection, lazily compressing at most once across all recipients. Connections that require per-connection framing — client masking, stateful sliding-window compression dictionaries, or fragmentation into smaller MaxFramePayload chunks — transparently fall back to regular sending.
func NewPreparedMessage ¶ added in v1.9.0
func NewPreparedMessage(typ MessageType, payload []byte) (*PreparedMessage, error)
NewPreparedMessage copies payload once into a pooled WebSocket server frame and freezes it into an immutable PreparedMessage. typ must be TextMessage or BinaryMessage (for text, payload must be valid UTF-8). Callers may immediately reuse or modify payload after NewPreparedMessage returns, and should call PreparedMessage.Release once the broadcast loop finishes.
func (*PreparedMessage) Len ¶ added in v1.9.0
func (m *PreparedMessage) Len() int
Len returns the uncompressed application payload length in bytes.
func (*PreparedMessage) Payload ¶ added in v1.9.0
func (m *PreparedMessage) Payload() []byte
Payload returns the immutable application payload slice.
func (*PreparedMessage) Release ¶ added in v1.9.0
func (m *PreparedMessage) Release()
Release ends the broadcaster's hold on m. Any connections that already queued m retain their in-flight read-only views safely until their socket writes complete, at which point the underlying buffer returns to UIO's pool. Calling Release more than once panics.
func (*PreparedMessage) Type ¶ added in v1.9.0
func (m *PreparedMessage) Type() MessageType
Type returns the WebSocket message type (TextMessage or BinaryMessage).
type RejectError ¶ added in v1.8.0
RejectError is what Server.Authorize returns to refuse an upgrade with a response of its choosing. Status is the HTTP status, 403 when zero or not a 4xx or 5xx code; Header is added to the response — all of it or none: one reserved or malformed name drops the whole header; Reason is its plain-text body, cut to 4 KiB on a whole character, which a uws client reports as HandshakeError.Reason.
func (*RejectError) Error ¶ added in v1.8.0
func (e *RejectError) Error() string
type Server ¶
type Server struct {
// Options configures the protocol, the transport and backpressure, and
// carries the Handler every connection reports to.
Options
// CheckOrigin accepts an upgrade request. Nil accepts every origin.
CheckOrigin func(*http.Request) bool
// Authorize decides an upgrade request that passed validation and
// CheckOrigin, before the server answers it. A nil error accepts it, and
// userdata becomes the connection's Userdata from OnOpen on (`uws.Conn`
// in the sugar; a stack's `ServerLayer` reports it through
// uio.FindLayer instead). On the ServeHTTP path Authorize runs on the
// http server's goroutine, before the connection is adopted. An error
// refuses it: a *RejectError with the status, header and reason it names,
// any other error with 403. A refused connection never reaches the
// Handler. Authorize runs on the connection's turn, so a slow check holds
// up that connection only; it must not block for long all the same. Nil
// accepts every request.
Authorize func(r *http.Request) (userdata any, err error)
// 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 NewServer ¶
NewServer returns a Server using opts. http.Server-style: the exported fields are the configuration, this constructor only fills them in.
func (*Server) Close ¶
Close permanently stops the server and requests transport shutdown. It returns once the shutdown is requested; a Serve running on the server returns after all event loops and connection tasks have exited.
func (*Server) Ready ¶ added in v1.8.0
func (s *Server) Ready() <-chan struct{}
Ready returns a channel closed once Serve has brought the transport up: the moment ServeHTTP begins accepting upgrades. A Server that never gets there — Serve failed to bind, or Close came first — never closes it, so a caller waiting on it must bound the wait. Mounting behind net/http, wait on this before taking traffic: an upgrade that arrives earlier gets HTTP 500.
func (*Server) Serve ¶
Serve starts the event loops and listens on each supplied 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.
type Stats ¶ added in v1.8.0
type Stats struct {
// Transport is the underlying uio.Events runtime snapshot.
Transport uio.Stats
// ActiveConnections is the number of open WebSocket connections whose
// upgrade handshake has completed.
ActiveConnections int64
// HandshakingConnections is the number of connections currently in the
// HTTP upgrade handshake.
HandshakingConnections int64
// TotalUpgrades counts connections that have completed the WebSocket
// upgrade handshake.
TotalUpgrades uint64
// HandshakeFailures counts upgrade handshakes that failed validation,
// origin/authorization checks, or timed out.
HandshakeFailures uint64
// BackpressureDrops counts non-blocking sends rejected with ErrBackpressure.
BackpressureDrops uint64
}
Stats is a point-in-time, zero-allocation runtime snapshot of a Server or Dialer. Counters live on cache-line-isolated stripes updated only at connection handshake/close boundaries and cold backpressure rejections, so message reads and writes pay zero overhead.
type TrafficObserver ¶ added in v1.8.0
TrafficObserver reports transport traffic. Implement it on the Handler to receive both directions of every connection.
Both callbacks are observation only. They must not call any method that sends or closes on the connection (SendText, SendBinary, Ping, Close, ...): a report is the result of I/O that just happened, and writing from it feeds the report it answers — it retires more bytes, which reports again. In uws the report can also run while the write lock a send holds is still held, so a write here deadlocks the connection. They must not block either. OutboundBuffered, PauseRead and ResumeRead are safe here: they do not acquire the write lock or write to the transport.
OnBytesRead runs in the connection's turn and never overlaps its Handler callbacks. OnBytesWritten runs wherever the transport finishes a send — a write turn, a writer goroutine, or the goroutine closing the connection, possibly with internal locks held — and may overlap the connection's Handler callbacks and OnBytesRead, so state it shares with them must be safe for concurrent use. Reports made inside a WebSocket batch handoff may be combined and delivered just after handoff, preserving their byte total.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
autobahn
|
|
|
server
command
|
|
|
examples
|
|
|
echo
command
|
|
|
nethttp
command
|
|
|
internal
|
|
|
compress
Package compress implements RFC 7692 message DEFLATE with bounded output and negotiated context takeover.
|
Package compress implements RFC 7692 message DEFLATE with bounded output and negotiated context takeover. |
|
extension
Package extension parses and negotiates WebSocket extension headers.
|
Package extension parses and negotiates WebSocket extension headers. |
|
frame
Package frame implements the wire-level WebSocket frame codec.
|
Package frame implements the wire-level WebSocket frame codec. |
|
handshake
Package handshake parses, validates, and builds RFC 6455 HTTP upgrades.
|
Package handshake parses, validates, and builds RFC 6455 HTTP upgrades. |