uws

package
v1.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 9, 2026 License: Apache-2.0 Imports: 30 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Go Reference Autobahn License

uws is a WebSocket server and client for Go, built on the uio event engine. The handshake, frame parsing and your handler all run in the connection's own turn on a shared worker pool, so a connection costs no goroutine of its own, and a message that arrives in one frame reaches you straight from the read buffer.

Highlights

  • Standards first. RFC 6455 framing and close handshake, RFC 7692 permessage-deflate, and a clean run of the Autobahn test suite.
  • Three ways in. A native server that parses the upgrade itself, an http.Handler for existing net/http servers, and a client.
  • Zero-copy reads. Frames are unmasked in place, and an unfragmented, uncompressed message is handed to OnMessage straight from the read buffer.
  • Send from anywhere. SendText, SendBinary, Send and Ping are safe from any goroutine and keep their order; they never block on the socket.
  • Batched replies. Small replies to the frames of one read are encoded together and handed to the socket as one write.
  • Bounded by design. Limits on frame and message size, explicit PauseRead/ResumeRead with MaxInboundBuffered TCP backpressure, an optional MaxOutboundBuffered hard limit on queued output, bounded handshake and close timeouts, and heartbeats on both ends.

Install

import "github.com/urpc/uio/uws"

The package ships inside the uio module; go get github.com/urpc/uio fetches it.

Quick start

package main

import (
	"log"

	"github.com/urpc/uio/uws"
)

type echo struct{}

func (echo) OnOpen(*uws.Conn)                  {}
func (echo) OnClose(*uws.Conn, uws.CloseEvent) {}

func (echo) OnMessage(c *uws.Conn, m uws.Message) {
	if m.Type == uws.TextMessage {
		_ = c.SendText(m.Text())
	} else {
		_ = c.SendBinary(m.Bytes())
	}
}

func main() {
	server := uws.NewServer(uws.Options{Handler: echo{}, EnableCompression: true})
	log.Fatal(server.Serve(":8080"))
}

Serve takes any number of addresses and returns once every connection has finished.

How it works

  1. Upgrade. Serve parses the HTTP upgrade natively; behind net/http the request is hijacked and the socket moved onto uio.
  2. Parse. Frames are unmasked in place. Text is validated as UTF-8, with a SIMD validator on amd64 with AVX2, and compressed messages are inflated.
  3. Handle. OnMessage runs in the connection's turn. The Handler callbacks of one connection are ordered and never overlap.
  4. Reply. What the handler sends is queued; small replies to one read's frames are batched into one write. Sends from other goroutines join the same queue in order.

Behind net/http

Server is also an http.Handler. Start its event loops with Serve() (no address), then mount it like any other handler:

server := uws.NewServer(uws.Options{Handler: echo{}})
go func() { log.Fatal(server.Serve()) }()

http.Handle("/ws", server)
log.Fatal(http.ListenAndServe(":8080", nil))

The handler takes over plain HTTP/1.1 connections. TLS and HTTP/2 connections cannot be moved onto uio's event loops: terminate TLS in a proxy in front, or let Serve take wss itself with TLSConfig. A request that arrives before Serve has started gets HTTP 500; Server.Ready closes a channel once the transport is up, so anything that mounts the handler programmatically — a proxy that builds it at start-up — can wait on it first.

Client

The callback form above suits one handler serving many connections. For a single connection used from one place, the pull form returns a ready client after the handshake:

client, err := uws.Dial(ctx, "ws://127.0.0.1:8080/")
if err != nil {
	log.Fatal(err)
}
defer client.Close(1000, "")

_ = client.SendText("hello")
for {
	message, err := client.ReadMessage(ctx)
	if err != nil {
		break // a *uws.CloseError once the queued messages ran out
	}
	log.Printf("%s", message.Payload)
}

uws.Dial uses uws.DefaultDialer, a default-options dialer that lives as long as the process. Dialer.DialClient is the same with a configured dialer, whose Options.Handler must be nil because the client owns the callbacks (uws.NewBlockingConn(conn) upgrades an open server or client *Conn inside OnOpen or OnMessage into the same *BlockingConn / *Client synchronous endpoint, offering ReadMessage, zero-alloc ReadMessageInto, and backpressured WriteText/WriteBinary/WriteMessage/Flush). A full message queue pauses the connection's reads via Conn.PauseRead without blocking event turns — TCP flow control then slows the peer — so a client must either keep reading or be closed; Client.Close stops further intake immediately and completes the close handshake, while ReadMessage drains messages queued before the close and then reports *uws.CloseError. With a heartbeat configured, a paused client keeps pinging on its non-blocking turns and closes if a Ping goes unanswered. Calling blocking methods on an event-loop turn returns ErrBlockingOnTurn.

The callback form, for one handler serving every connection a dialer makes:

type client struct{}

func (client) OnOpen(c *uws.Conn)                  { _ = c.SendText("hello") }
func (client) OnMessage(c *uws.Conn, m uws.Message) { log.Printf("%s", m.Payload) }
func (client) OnClose(c *uws.Conn, e uws.CloseEvent) {
	if e.Err != nil {
		log.Println("closed:", e.Err)
	}
}

dialer := uws.NewDialer(uws.Options{Handler: client{}})
if err := dialer.Dial(ctx, "ws://127.0.0.1:8080/", nil); err != nil {
	log.Fatal(err)
}

Dial returns once the upgrade request is sent and the handshake finishes in the background; the connection reaches the application only through the handler. Its third argument is the connection's userdata, available as Conn.Userdata in every callback, so one stateless handler serves every dial. An error from Dial means no connection was made and no callback follows, uio.ErrFirstTurnRefused when a custom Executor declines the connection's first turn. After a nil error, OnOpen means the connection is ready, and OnClose always follows, with the cause in CloseEvent.Err; a failed handshake calls it without OnOpen. The context bounds the dial and the handshake, not the connection after it.

Configuration

Options holds every setting; Server and Dialer embed the same type and the zero value means the defaults, so the two ends cannot drift apart. Options are read when Serve or Dial first starts the transport and never again.

Field Default What it does
Subprotocols none Protocols to negotiate; a server prefers the order given.
MaxHeaderBytes 32 KiB Upgrade headers this end reads: the request on a server's native Serve path, the response on a dialer. Behind net/http, http.Server.MaxHeaderBytes applies instead.
MaxFramePayload 16 MiB Largest frame read; larger outgoing messages are fragmented.
MaxMessageSize 64 MiB Largest message, after decompression.
EnableCompression off Negotiates permessage-deflate.
CompressionLevel default flate level 1-9 when compression is on; there is no level 0.
KeepCompressionContext off Keeps this end's compression history between messages; off starts every message fresh and asks the same of the peer.
DisableUTF8Check off Skips text validation for trusted peers. Not RFC compliant.
HandshakeTimeout 10 s Bounds the HTTP upgrade.
CloseTimeout 5 s Bounds the close handshake.
HeartbeatInterval off Pings the peer at this interval; servers and dialers alike.
HeartbeatTimeout 2 × interval Closes the connection when a ping gets no pong in time.
Pollers uio default Event loops.
ReadBufferSize 4 KiB Bytes per socket read; it also sizes the write batch blocks (clamped to 4-64 KiB). Over TLS a record carries up to 16 KiB: a read smaller than that splits one record across several rounds, so a wss server moving bulk data reads about twice as fast with 16 KiB and half again with 64 KiB.
WriteCoalesce 4 KiB Writes smaller than this join the connection's outbound batch instead of taking a send of their own; a negative value turns size-based buffering off.
ReusePort off Sets SO_REUSEPORT on listeners.
Executor uio default Runs connection and write turns on the native backend; the stdio backend does not use it.
MaxInboundBuffered 64 KiB Transport receive bound, allowing Conn.PauseRead to stop socket reads and apply TCP backpressure.
MaxOutboundBuffered off Hard limit on one connection's queued output from any sender: a send past it returns ErrBackpressure and queues nothing. Size it to fit the largest message you send.

A Server adds CheckOrigin and Authorize, and a Dialer adds Header and RequestHeader (see Authentication). The Handler lives in Options, shared by every connection a server accepts or a dialer dials, with per-dial state passed as Dial's userdata. The underlying transport is built from these options and is not otherwise exposed; Executor is the scheduling escape hatch. Invalid combinations, such as a compression level outside 1-9, make Serve and Dial return ErrInvalidOptions.

Backpressure. Output is bounded at the sender by MaxOutboundBuffered: past the limit SendText, SendBinary and Ping return ErrBackpressure and queue nothing, so the caller decides to drop, retry later or close.

For a relay or an application work queue, Conn.PauseRead(), Conn.ResumeRead() and Conn.ReadPaused() provide a concurrency-safe read switch across plain TCP, TLS (wss://) and layer stacks alike. Pause from OnMessage stops before the next frame, including frames in the same socket read; an already running callback may finish. The frames wait in the transport, which stops reading the socket once MaxInboundBuffered is reached; resume delivers them without new network input. Resuming without a pause does nothing. Calls are idempotent and are not reference counted, so one flow controller should own the switch. Both return ErrNotReady before the WebSocket opens and ErrClosed after closing begins.

Conn.OutboundBuffered() reports the WebSocket write batch plus the queue below it, including framing and lower-layer overhead. It is a concurrent snapshot: during a handoff it may briefly count bytes twice. Use it for watermarks; MaxOutboundBuffered provides the hard write limit. It is safe to query from TrafficObserver.OnBytesWritten, where a controller can resume the upstream connection after its destination drains. Call pace after forwarding to the destination and from its OnBytesWritten callback; resuming an upstream that is not paused costs nothing. The second observation also catches a drain that raced with installing the pause:

func pace(upstream, destination *uws.Conn, high, low int) {
	if destination.OutboundBuffered() >= high {
		if err := upstream.PauseRead(); err != nil {
			return
		}
	}
	if destination.OutboundBuffered() <= low {
		_ = upstream.ResumeRead()
	}
}

Explicit pauses also work over TLS. They delay Ping/Pong and other incoming control frames; heartbeat deadlines continue to run, and a local Close releases UWS's own pauses to finish its handshake. A paused connection also keeps its peer's end of stream behind the frames it holds: a peer that sends and closes is answered after ResumeRead, so without a heartbeat or read deadline a paused connection whose peer left stays open until then. A custom layer stack uses its configured Events.MaxInboundBuffered, or UIO's default receive bound while explicit reads are paused.

Traffic metrics. A Handler that also implements TrafficObserver sees transport bytes in both directions. Both callbacks are observation only: do not call anything that sends or closes on the connection from them, and do not block. A report is the result of I/O that just happened, and a send from it feeds the report it answers; OnBytesWritten can also run while the write lock a send holds is held, so a send there deadlocks the connection. OnBytesRead runs in the connection's turn like the other callbacks; OnBytesWritten runs wherever a send completes and may overlap them, so keep what it touches safe for concurrent use. OutboundBuffered, PauseRead and ResumeRead are safe in these callbacks:

func (m metrics) OnBytesRead(c *uws.Conn, n int)  { m.read.Add(n) }
func (m metrics) OnBytesWritten(c *uws.Conn, n int) { m.written.Add(n) }

Authentication

The upgrade request can carry credentials, and the server can refuse it before the WebSocket exists, so a rejected client costs no handshake and no callback:

dialer := &uws.Dialer{
	Header: http.Header{"Authorization": {"Bearer " + token}},
}

server := uws.NewServer(uws.Options{Handler: app{}})
server.Authorize = func(r *http.Request) (any, error) {
	user, err := verify(r.Header.Get("Authorization"))
	if err != nil {
		return nil, &uws.RejectError{Status: http.StatusUnauthorized, Reason: "bad token"}
	}
	return user, nil // the connection's Userdata from OnOpen on
}

Dialer.Header goes with every dial; Dialer.RequestHeader(userdata) adds per-dial headers on top. Headers the handshake sets itself are refused with ErrInvalidOptions: Host, Upgrade, Connection, Content-Length, Transfer-Encoding, Expect, and Sec-WebSocket-Key, -Version, -Protocol, -Extensions and -Accept. Authorize runs after the request passed validation and CheckOrigin, on the native path and behind net/http alike. A *RejectError answers with its status, header and reason; any other error with 403. The answer is sent before the connection closes, and the client gets it as a *HandshakeError — in CloseEvent.Err, or from DialClient through errors.As — carrying the status, the header and the reason. Without TLS the credentials travel in clear text: serve wss with TLSConfig, whose state Authorize sees on r.TLS — the server name asked for, a client certificate.

Secure WebSockets (wss)

Options.TLSConfig makes a server a wss one and lets a dialer speak wss:// — a crypto/tls configuration, run by uio/utls under the WebSocket protocol:

server := uws.NewServer(uws.Options{
	Handler:   handler,
	TLSConfig: &tls.Config{Certificates: certs},
})

dialer := uws.NewDialer(uws.Options{
	Handler:   handler,
	TLSConfig: &tls.Config{}, // system roots; each dial verifies its URL's host
})
err := dialer.Dial(ctx, "wss://example.org:443/socket", nil)

A dialer with a TLSConfig still dials ws:// in the clear; without one it refuses wss://. The TLS handshake runs before the WebSocket one, within HandshakeTimeout: one that fails fails the dial with its cause, and the Handler hears nothing of the connection. Behind net/http, ServeHTTP runs no TLS of its own and refuses a request that arrived over TLS: terminate TLS elsewhere and pass the plain HTTP/1.1 upgrade through, or let Serve take wss:// itself with a TLSConfig. A TLS record carries up to 16 KiB, so a ReadBufferSize of 16 KiB or more reads one record per syscall.

As a protocol layer

ServerLayer and ClientLayer run the WebSocket protocol as a uio.Layer, for stacks of your own — TLS, an obfuscation, a tunnel, in any order, on an uio.Events you configure:

listener, err := server.Listen(addr, uio.WithLayers(
	utls.ServerLayer(utls.LayerOptions{TLSConfig: tlsConfig}),
	uws.ServerLayer(uws.LayerOptions{Authorize: checkToken}), tunnel,
))
conn, err := client.DialContext(ctx, "tcp://example.org:443", uio.WithLayers(
	utls.ClientLayer(utls.LayerOptions{TLSConfig: tlsConfig}),
	uws.ClientLayer(uws.LayerOptions{Target: "wss://example.org/tunnel"}), tunnel,
))

The layer carries a byte stream: what the layer above writes leaves as Binary messages, and each message that arrives is handed up once whole, message boundaries dropped. It answers Pings, runs the heartbeat, answers a peer's Close, and sends one as the connection closes from above; a dial returns once the handshake succeeded, and reports a refusal as a *HandshakeError. The protocol's settings are Options' own; the transport's — Handler, Pollers, ReusePort, Executor, TLSConfig, MaxInboundBuffered, MaxOutboundBuffered — belong to the Events, and options that name them fail every connection with ErrInvalidOptions (LayerOptions.Validate reports it up front). A client layer takes the URL its upgrade request names as LayerOptions.Target, one target per layer; a server layer refuses a Target. For messages, keep to Server and Dialer.

Rules of the road

  • Payloads are borrowed. Message.Payload is valid until OnMessage returns. Call Message.Clone to keep it or hand it to another goroutine. Message.Text and Message.Bytes hand the payload back to SendText and SendBinary without copying, for echoes.
  • Accepted is not delivered. A nil error from SendText, SendBinary or Ping means the message was queued in order, not that the peer has it. Outbound queues are bounded by MaxOutboundBuffered, past which non-blocking sends return ErrBackpressure (while BlockingConn.Write* suspends off-turn callers until space drains).
  • State without locks. The Handler callbacks of one connection never overlap, so state kept with SetUserdata needs no locking from them; TrafficObserver.OnBytesWritten is the exception, and it must only observe — never send, close or block.
  • Closing. Conn.Close(code, reason) queues its close frame after everything already accepted and returns; the connection then completes the handshake with the peer, which CloseTimeout bounds. Protocol errors close with 1002, invalid UTF-8 with 1007, oversized messages with 1009.
  • Lifecycle. Server.Close and Dialer.Close request shutdown and return at once, so they are safe inside callbacks. A server or dialer cannot be restarted.

The API reference documents every type and method.

License

Apache License 2.0

The Go gopher in the banner is based on the original design by Renée French, licensed under CC BY 4.0.

Documentation

Overview

Package uws provides an asynchronous WebSocket server and client built on UIO.

Index

Constants

View Source
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
)
View Source
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
)
View Source
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

View Source
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
)
View Source
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.

View Source
var ErrBlockingOnTurn = uio.ErrBlockingOnTurn

ErrBlockingOnTurn reports an attempt to invoke a blocking operation on a connection turn or event-loop goroutine.

View Source
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.

func (*BlockingConn) WriteText added in v1.9.0

func (c *BlockingConn) WriteText(ctx context.Context, text string) error

WriteText sends a text WebSocket message, suspending when 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.

func Dial added in v1.8.0

func Dial(ctx context.Context, addr string, opts ...BlockingOption) (*Client, error)

Dial connects with DefaultDialer and returns the synchronous client once the WebSocket handshake completes.

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

func (c *Conn) Close(code uint16, reason string) error

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) IsClosed

func (c *Conn) IsClosed() bool

IsClosed reports whether the connection has closed.

func (*Conn) LocalAddr

func (c *Conn) LocalAddr() net.Addr

LocalAddr returns the local transport address.

func (*Conn) OutboundBuffered added in v1.9.0

func (c *Conn) OutboundBuffered() int

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

func (c *Conn) PauseRead() error

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) Ping

func (c *Conn) Ping(payload []byte) error

Ping sends a ping control frame with up to 125 bytes of payload.

func (*Conn) ReadPaused added in v1.9.0

func (c *Conn) ReadPaused() bool

ReadPaused reports whether PauseRead currently holds incoming WebSocket frames.

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr returns the peer transport address.

func (*Conn) Request added in v1.1.0

func (c *Conn) Request() *http.Request

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

func (c *Conn) ResumeRead() error

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

func (c *Conn) SendBinary(payload []byte) error

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

func (c *Conn) SendText(payload string) error

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

func (c *Conn) SetDeadline(deadline time.Time) error

SetDeadline forwards the transport read and write deadline. A zero value clears it.

func (*Conn) SetNoDelay added in v1.1.0

func (c *Conn) SetNoDelay(noDelay bool) error

SetNoDelay controls whether the underlying TCP connection uses Nagle's algorithm.

func (*Conn) SetReadDeadline added in v1.1.0

func (c *Conn) SetReadDeadline(deadline time.Time) error

SetReadDeadline forwards the transport read deadline. A zero value clears it.

func (*Conn) SetUserdata added in v1.1.0

func (c *Conn) SetUserdata(value any)

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

func (c *Conn) SetWriteDeadline(deadline time.Time) error

SetWriteDeadline forwards the transport write deadline. A zero value clears it.

func (*Conn) Subprotocol

func (c *Conn) Subprotocol() string

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.

func (*Conn) Userdata added in v1.1.0

func (c *Conn) Userdata() any

Userdata returns the user data associated with the connection. It is not safe for concurrent use from multiple goroutines.

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 NewDialer

func NewDialer(opts Options) *Dialer

NewDialer returns a Dialer using opts.

func (*Dialer) Close

func (d *Dialer) Close(err error) error

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

func (d *Dialer) Dial(ctx context.Context, addr string, userdata any) error

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.

func (*Dialer) Stats added in v1.8.0

func (d *Dialer) Stats() Stats

Stats returns a point-in-time, zero-allocation runtime snapshot of d.

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

func (m Message) Bytes() []byte

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.

func (Message) Clone

func (m Message) Clone() Message

Clone returns an independently owned copy of m.

func (Message) Text added in v1.8.0

func (m Message) Text() string

Text returns Payload as a string without copying, for the common echo — handing a text message straight back to SendText. Like Payload, it is valid only until OnMessage returns; call Clone to keep either past it.

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

type RejectError struct {
	Status int
	Header http.Header
	Reason string
}

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

func NewServer(opts Options) *Server

NewServer returns a Server using opts. http.Server-style: the exported fields are the configuration, this constructor only fills them in.

func (*Server) Close

func (s *Server) Close(err error) error

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

func (s *Server) Serve(addrs ...string) error

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.

func (*Server) Stats added in v1.8.0

func (s *Server) Stats() Stats

Stats returns a point-in-time, zero-allocation runtime snapshot of s.

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

type TrafficObserver interface {
	OnBytesRead(*Conn, int)
	OnBytesWritten(*Conn, int)
}

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.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL