Die API-Referenz stammt aus den Go-Doc-Kommentaren im Quellcode und ist auf Englisch verfasst.
package netplay
import "github.com/nsgo-dev/game/pkg/online/netplay"Übersicht
Package netplay provides cross-target multiplayer primitives for NSGo games:
- Transport abstraction with deterministic in-memory loopback, pure-Go RFC 6455 WebSocket (native + browser WebAssembly), HTTP/3 QUIC WebTransport (native + browser WebAssembly), and native UDP transports.
- Server-authoritative state replication with bitmask delta compression, snapshot interpolation, and client-side prediction/reconciliation.
- Deterministic lockstep and GGPO-style rollback netcode with periodic checksum verification and desync detection.
- A Relay that forwards peer-to-peer sessions between RelayTransports over WebSocket, WebTransport, or UDP for players who cannot reach each other directly.
Index
- Konstanten
- Variablen
- func ChecksumBytes(data []byte) uint64
- func EncodeCaptureRecord(r CaptureRecord) ([]byte, error)
- func WebTransportSupported() bool
- type Auth
- type CaptureDirection
- type CaptureOptions
- type CaptureRecord
- type Channel
- type ClientWorld
- func NewClientWorld(transport Transport, serverID PeerID) *ClientWorld
- func (c *ClientWorld) Entity(id EntityID) (EntityState, bool)
- func (c *ClientWorld) Epoch() (uint32, bool)
- func (c *ClientWorld) Err() error
- func (c *ClientWorld) Interpolate(renderTick float64) []EntityState
- func (c *ClientWorld) LastReconcileError() float32
- func (c *ClientWorld) LatestTick() (uint32, bool)
- func (c *ClientWorld) PendingPredictions(id EntityID) int
- func (c *ClientWorld) Poll() int
- func (c *ClientWorld) Predict(localEntity EntityID, input any, apply func(*EntityState, any))
- func (c *ClientWorld) PredictedState(id EntityID) (EntityState, bool)
- func (c *ClientWorld) Reconciliations() int
- func (c *ClientWorld) Reset()
- type ComponentState
- type ConnState
- type DesyncEvent
- type EntityID
- type EntityState
- type InboxLimits
- type InboxReporter
- type InboxStats
- type InputFrame
- type KickError
- type LockstepConfig
- type LockstepSession
- func NewLockstepSession(cfg LockstepConfig) *LockstepSession
- func (s *LockstepSession) Active() bool
- func (s *LockstepSession) AddPeer(id PeerID) (uint32, error)
- func (s *LockstepSession) Desyncs() []DesyncEvent
- func (s *LockstepSession) Members() []PeerID
- func (s *LockstepSession) Poll()
- func (s *LockstepSession) RemovePeer(id PeerID) (uint32, error)
- func (s *LockstepSession) Step() bool
- func (s *LockstepSession) SubmitInput(in InputFrame) error
- func (s *LockstepSession) Tick() uint32
- type LoopbackConfig
- type LoopbackHub
- func NewLoopbackHub(cfg LoopbackConfig) *LoopbackHub
- func (h *LoopbackHub) AddPeer(id PeerID) *LoopbackTransport
- func (h *LoopbackHub) Advance(dt time.Duration)
- func (h *LoopbackHub) Config() LoopbackConfig
- func (h *LoopbackHub) InFlight() int
- func (h *LoopbackHub) Now() time.Duration
- func (h *LoopbackHub) RemovePeer(id PeerID)
- func (h *LoopbackHub) SetConfig(cfg LoopbackConfig)
- type LoopbackTransport
- func (t *LoopbackTransport) Close() error
- func (t *LoopbackTransport) InboxStats() InboxStats
- func (t *LoopbackTransport) LocalID() PeerID
- func (t *LoopbackTransport) Peers() []PeerID
- func (t *LoopbackTransport) Recv() (Packet, bool)
- func (t *LoopbackTransport) Send(to PeerID, ch Channel, payload []byte) error
- func (t *LoopbackTransport) SetInboxLimits(l InboxLimits)
- type OutboxLimits
- type OutboxReporter
- type OutboxStats
- type Packet
- type PeerEvent
- type PeerEventKind
- type PeerEvents
- type PeerID
- type RejectError
- type Relay
- type RelayConfig
- type RelayServer
- type RelayStats
- type RelayTransport
- func NewRelayTransport(inner Transport, cfg RelayTransportConfig) *RelayTransport
- func (rt *RelayTransport) Close() error
- func (rt *RelayTransport) InboxStats() InboxStats
- func (rt *RelayTransport) LocalID() PeerID
- func (rt *RelayTransport) Peers() []PeerID
- func (rt *RelayTransport) Recv() (Packet, bool)
- func (rt *RelayTransport) Send(to PeerID, ch Channel, payload []byte) error
- func (rt *RelayTransport) SetInboxLimits(l InboxLimits)
- type RelayTransportConfig
- type ReplicationStats
- type RollbackConfig
- type RollbackSession
- func NewRollbackSession(cfg RollbackConfig) *RollbackSession
- func (s *RollbackSession) Active() bool
- func (s *RollbackSession) AddPeer(id PeerID) (uint32, error)
- func (s *RollbackSession) ConfirmedTick() int64
- func (s *RollbackSession) Desyncs() []DesyncEvent
- func (s *RollbackSession) Members() []PeerID
- func (s *RollbackSession) Poll() error
- func (s *RollbackSession) RemovePeer(id PeerID) (uint32, error)
- func (s *RollbackSession) Stats() RollbackStats
- func (s *RollbackSession) Step(localInput InputFrame) error
- func (s *RollbackSession) Tick() uint32
- func (s *RollbackSession) Waiting() []PeerID
- type RollbackStats
- type ServerWorld
- func NewServerWorld(transport Transport) *ServerWorld
- func (w *ServerWorld) Despawn(id EntityID) bool
- func (w *ServerWorld) Entities() []EntityState
- func (w *ServerWorld) Entity(id EntityID) (EntityState, bool)
- func (w *ServerWorld) Epoch() uint32
- func (w *ServerWorld) PeerErr(peer PeerID) error
- func (w *ServerWorld) SetEpoch(epoch uint32)
- func (w *ServerWorld) SetMaxSnapshotSize(n int)
- func (w *ServerWorld) Spawn(state EntityState) EntityID
- func (w *ServerWorld) Stats() ReplicationStats
- func (w *ServerWorld) Step(tick uint32) error
- func (w *ServerWorld) Update(id EntityID, state EntityState) bool
- type SimState
- type Transport
- type UDPClient
- func DialUDP(addr string, serverKey *ecdh.PublicKey, token []byte) (*UDPClient, error)
- func (c *UDPClient) Close() error
- func (c *UDPClient) Err() error
- func (c *UDPClient) InboxStats() InboxStats
- func (c *UDPClient) LocalID() PeerID
- func (c *UDPClient) Peers() []PeerID
- func (c *UDPClient) Reconnect() error
- func (c *UDPClient) Recv() (Packet, bool)
- func (c *UDPClient) Resumed() bool
- func (c *UDPClient) Send(to PeerID, ch Channel, payload []byte) error
- func (c *UDPClient) SetInboxLimits(l InboxLimits)
- func (c *UDPClient) State() ConnState
- type UDPServer
- func ListenUDPServer(addr string, serverID PeerID, auth Auth) (*UDPServer, error)
- func (s *UDPServer) Addr() stdnet.Addr
- func (s *UDPServer) Close() error
- func (s *UDPServer) Err() error
- func (s *UDPServer) InboxStats() InboxStats
- func (s *UDPServer) Kick(peer PeerID, reason string) error
- func (s *UDPServer) LocalID() PeerID
- func (s *UDPServer) NextEvent() (PeerEvent, bool)
- func (s *UDPServer) Peers() []PeerID
- func (s *UDPServer) PublicKey() *ecdh.PublicKey
- func (s *UDPServer) Recv() (Packet, bool)
- func (s *UDPServer) Send(to PeerID, ch Channel, payload []byte) error
- func (s *UDPServer) SetInboxLimits(l InboxLimits)
- type UDPTransport
- func ListenUDP(addr string, localID PeerID) (*UDPTransport, error)
- func (u *UDPTransport) AddPeer(id PeerID, addr string) error
- func (u *UDPTransport) AddPeerKey(id PeerID, addr string, key [32]byte) error
- func (u *UDPTransport) Addr() stdnet.Addr
- func (u *UDPTransport) Close() error
- func (u *UDPTransport) Err() error
- func (u *UDPTransport) InboxStats() InboxStats
- func (u *UDPTransport) LocalID() PeerID
- func (u *UDPTransport) Peers() []PeerID
- func (u *UDPTransport) Recv() (Packet, bool)
- func (u *UDPTransport) RemovePeer(id PeerID)
- func (u *UDPTransport) Send(to PeerID, ch Channel, payload []byte) error
- func (u *UDPTransport) SetInboxLimits(l InboxLimits)
- type WebSocketServer
- func ListenWebSocket(addr string, serverID PeerID, auth Auth) (*WebSocketServer, error)
- func ListenWebSocketTLS(addr string, serverID PeerID, auth Auth, config *tls.Config, allowedOrigins []string) (*WebSocketServer, error)
- func ListenWebSocketTLSFiles(addr string, serverID PeerID, auth Auth, certFile, keyFile string, allowedOrigins []string) (*WebSocketServer, error)
- func (s *WebSocketServer) Addr() stdnet.Addr
- func (s *WebSocketServer) Close() error
- func (s *WebSocketServer) InboxStats() InboxStats
- func (s *WebSocketServer) Kick(peer PeerID, reason string) error
- func (s *WebSocketServer) LocalID() PeerID
- func (s *WebSocketServer) NextEvent() (PeerEvent, bool)
- func (s *WebSocketServer) OutboxStats() OutboxStats
- func (s *WebSocketServer) Peers() []PeerID
- func (s *WebSocketServer) Recv() (Packet, bool)
- func (s *WebSocketServer) Send(to PeerID, ch Channel, payload []byte) error
- func (s *WebSocketServer) SetInboxLimits(l InboxLimits)
- func (s *WebSocketServer) SetOutboxLimits(l OutboxLimits)
- type WebSocketTransport
- func DialWebSocket(rawURL string, token []byte) (*WebSocketTransport, error)
- func (wt *WebSocketTransport) Close() error
- func (wt *WebSocketTransport) Err() error
- func (wt *WebSocketTransport) InboxStats() InboxStats
- func (wt *WebSocketTransport) LocalID() PeerID
- func (wt *WebSocketTransport) Peers() []PeerID
- func (wt *WebSocketTransport) Reconnect() error
- func (wt *WebSocketTransport) Recv() (Packet, bool)
- func (wt *WebSocketTransport) Resumed() bool
- func (wt *WebSocketTransport) Send(to PeerID, ch Channel, payload []byte) error
- func (wt *WebSocketTransport) SetInboxLimits(l InboxLimits)
- func (wt *WebSocketTransport) State() ConnState
- type WebTransportOptions
- type WebTransportServer
- func ListenWebTransport(addr string, serverID PeerID, auth Auth, cfg *tls.Config, allowedOrigins []string) (*WebTransportServer, error)
- func ListenWebTransportFiles(addr string, serverID PeerID, auth Auth, certFile, keyFile string, allowedOrigins []string) (*WebTransportServer, error)
- func (s *WebTransportServer) Addr() stdnet.Addr
- func (s *WebTransportServer) Close() error
- func (s *WebTransportServer) InboxStats() InboxStats
- func (s *WebTransportServer) LocalID() PeerID
- func (s *WebTransportServer) NextEvent() (PeerEvent, bool)
- func (s *WebTransportServer) OutboxStats() OutboxStats
- func (s *WebTransportServer) Peers() []PeerID
- func (s *WebTransportServer) Recv() (Packet, bool)
- func (s *WebTransportServer) Send(to PeerID, ch Channel, payload []byte) error
- func (s *WebTransportServer) SetInboxLimits(l InboxLimits)
- func (s *WebTransportServer) SetOutboxLimits(l OutboxLimits)
- type WebTransportTransport
- func DialWebTransport(rawURL string, token []byte, opts WebTransportOptions) (*WebTransportTransport, error)
- func (wt *WebTransportTransport) Close() error
- func (wt *WebTransportTransport) Err() error
- func (wt *WebTransportTransport) InboxStats() InboxStats
- func (wt *WebTransportTransport) LocalID() PeerID
- func (wt *WebTransportTransport) Peers() []PeerID
- func (wt *WebTransportTransport) Reconnect() error
- func (wt *WebTransportTransport) Recv() (Packet, bool)
- func (wt *WebTransportTransport) Resumed() bool
- func (wt *WebTransportTransport) Send(to PeerID, ch Channel, payload []byte) error
- func (wt *WebTransportTransport) SetInboxLimits(l InboxLimits)
- func (wt *WebTransportTransport) State() ConnState
Konstanten
const (
// DefaultOutboxFrames is the most frames a WebSocketServer or WebTransportServer holds for one client when OutboxLimits.Frames is zero, as many as a Relay holds for one member.
DefaultOutboxFrames = 256
// DefaultOutboxBytes is the most bytes of frames a WebSocketServer or WebTransportServer holds for one client when OutboxLimits.Bytes is zero.
DefaultOutboxBytes = 4 << 20
)const (
// DefaultUnreliableInbox is the most ChannelUnreliable packets a transport's inbox holds from one peer when InboxLimits.Unreliable is zero.
DefaultUnreliableInbox = 4096
// DefaultReliableInbox is the most ChannelReliableOrdered packets a WebSocketServer's, WebTransportServer's, or RelayTransport's inbox holds from one peer when InboxLimits.Reliable is zero.
DefaultReliableInbox = 16384
// DefaultReliableInboxWarning is the ChannelReliableOrdered backlog that raises a warning when InboxLimits.ReliableWarning is zero.
DefaultReliableInboxWarning = 4096
)const CaptureVersion = 1CaptureVersion is the version of the JSON Lines packet capture format written by NewCaptureTransport and read by ReadCapture.
const (
// DefaultMaxSnapshotSize is the largest snapshot payload a ServerWorld passes to Transport.Send unless SetMaxSnapshotSize changes it. It fits every transport in this package: UDP datagrams (65000 bytes), relay messages (MaxRelayPayload) and WebSocket frames.
DefaultMaxSnapshotSize = 60000
)const MaxEntitiesPerSnapshot = 1 << 16MaxEntitiesPerSnapshot bounds a full snapshot's entity count. The map is allocated before each entity is read, so a corrupt 3.8MB packet claiming a million entities would reserve hundreds of megabytes before failing (#546).
const MaxJoinStateSize = 16 << 20MaxJoinStateSize is the largest snapshot, as returned by SimState.Save, that a host sends a joining peer. AddPeer refuses a peer with ErrPayloadTooLarge while the state is larger, and a join whose state has grown past it by the join tick is turned into a leave at that tick.
const (
// MaxRelayPayload is the largest payload RelayTransport.Send accepts: what fits in one UDP datagram after the relay's and the transport's headers.
MaxRelayPayload = 64000
)Relay wire format, version 1. Every relay frame travels as one ChannelUnreliable packet of the inner client or server transport, because reliability is end to end between the two RelayTransports, not per hop:
client to relay: version(1) to(4) body relay to client: version(1) from(4) body
A frame from the relay itself has from 0 and carries a control message:
members: version(1) 0(4) relayCtlMembers(1) epoch(4) count(2) peer(4)...
The epoch counts the session's membership changes. The relay sends the membership again every second with the same epoch, and a client compares epochs as serial numbers, so the counter may wrap.
A body between two peers is one of:
unreliable: relayBodyUnreliable(1) seq(4) payload reliable: relayBodyReliable(1) seq(4) payload ack: relayBodyAck(1) next(4) mask(8)
An ack says every reliable seq below next arrived, and bit i of mask says next+1+i arrived too, so the sender retransmits only what is missing.
const MaxTokenSize = 4096MaxTokenSize is the largest credential a client may present in the handshake.
const ReplicationVersion = 2ReplicationVersion is the version of the replication wire protocol that ServerWorld and ClientWorld speak. Version 2 added the replication epoch; peers of other versions cannot exchange snapshots and are refused with ErrReplicationVersion.
Variablen
var (
// ErrNotHost is returned by AddPeer and RemovePeer on a peer that is not the match's host: only the host changes who takes part.
ErrNotHost = errors.New("net: only the match's host changes its peers")
// ErrHostLeave is returned by RemovePeer for the host itself. The host cannot leave a running match; end the match instead.
ErrHostLeave = errors.New("net: the host cannot leave the match")
// ErrPeerRejoin is returned by AddPeer for a peer that has left the match, however long ago: a peer that comes back joins under a new ID, as a relay or server assigns one.
ErrPeerRejoin = errors.New("net: a peer that left cannot rejoin under the same ID")
// ErrSessionBacklog is returned once per peer, wrapped with the peer's ID, by the next LockstepSession.SubmitInput or RollbackSession.Step or Poll after more messages wait for that remote peer than a session keeps for a peer the transport cannot reach (4096). Messages to that peer are dropped from then on, so it has missed part of the match and cannot go on in it: the host removes it, or the match ends.
ErrSessionBacklog = errors.New("net: too many messages wait for an unreachable peer")
)var (
// ErrRejected matches (with errors.Is) the *RejectError a client gets when the server refuses its handshake.
ErrRejected = errors.New("net: connection rejected")
// ErrDisconnected is returned when sending on a client whose connection dropped, or to a server peer inside its grace period.
ErrDisconnected = errors.New("net: peer disconnected")
// ErrTokenTooLarge is returned when a token exceeds MaxTokenSize.
ErrTokenTooLarge = errors.New("net: token too large")
// ErrInvalidKey is returned when a Noise X25519 key is missing or uses another curve, or when AddPeerKey receives an all-zero key.
ErrInvalidKey = errors.New("net: invalid key")
// ErrSequenceExhausted is returned when a UDP session or keyed peer reaches the end of its 32-bit sequence space and cannot send without reusing an AEAD nonce. Call Reconnect (or re-register the peer with a new key) to rekey.
ErrSequenceExhausted = errors.New("net: session sequence exhausted")
// ErrKicked matches (with errors.Is) the *KickError a client gets when the server ends its session with WebSocketServer.Kick or UDPServer.Kick.
ErrKicked = errors.New("net: kicked by server")
)var (
// ErrClosed is returned when operating on a closed transport.
ErrClosed = errors.New("net: transport closed")
// ErrUnknownPeer is returned when sending to a peer that is not connected.
ErrUnknownPeer = errors.New("net: unknown peer")
// ErrInvalidPacket is returned when a wire frame is malformed or truncated.
ErrInvalidPacket = wsproto.ErrInvalidPacket
// ErrPayloadTooLarge is returned when a payload exceeds transport limits.
ErrPayloadTooLarge = wsproto.ErrPayloadTooLarge
// ErrUnsupportedChannel is returned when a transport cannot provide the delivery guarantees the requested channel asks for.
ErrUnsupportedChannel = errors.New("net: channel not supported by transport")
// ErrReceiveFailed is returned, wrapping the socket's error, by a transport whose socket failed so that it can no longer receive.
ErrReceiveFailed = errors.New("net: receive failed")
)var ErrRelayBacklog = errors.New("net: relay backlog full")ErrRelayBacklog is returned by RelayTransport.Send when a peer has not acknowledged the last 1024 reliable messages sent to it, so the sender stops instead of buffering without bound.
var ErrReplicationVersion = errors.New("net: unsupported replication protocol version")ErrReplicationVersion reports a replication message from a peer that speaks another version of the replication wire protocol than ReplicationVersion, such as a client or server built with an older release of this package. ClientWorld.Err and ServerWorld.PeerErr return it wrapped, with both versions.
var ErrRollbackStalled = fmt.Errorf("%w: waiting for remote input", ErrRollbackWindowExceeded)ErrRollbackStalled is returned by RollbackSession.Step, which then simulates no tick, while the oldest tick still waiting for a remote peer's input is MaxRollback ticks back: simulating further would put that tick beyond the snapshots kept, where its input could no longer be rolled back to. It matches ErrRollbackWindowExceeded with errors.Is. Unlike a late input beyond the window, it is temporary: Step advances again once the input arrives or the host removes the peer. Step names each peer it waits for, as Waiting returns them; a host removes one that keeps the match stalled, since a stalled session sends that peer nothing more and so never reports it with ErrSessionBacklog.
var ErrRollbackWindowExceeded = errors.New("net: rollback window exceeded")ErrRollbackWindowExceeded is returned when a late remote input arrives for a tick older than the retained MaxRollback snapshot window. RollbackSession.Step also returns it, as ErrRollbackStalled, while a remote peer's inputs are MaxRollback ticks behind.
ErrWebTransportUnavailable is returned by DialWebTransport in browsers that do not expose the WebTransport API.
Funktionen
func ChecksumBytes(data []byte) uint64ChecksumBytes computes a deterministic 64-bit FNV-1a checksum over data.
func EncodeCaptureRecord(r CaptureRecord) ([]byte, error)EncodeCaptureRecord validates and encodes one CaptureRecord as a single compact JSON line (without a trailing newline). If r.Version is 0, CaptureVersion is written automatically.
func WebTransportSupported() boolWebTransportSupported reports whether WebTransport is available in the current runtime. On native targets it always returns true.
Typen
type Auth struct {
// Verify checks the credential a client presented and the ID the server is about to assign it. A non-nil error rejects the client: it never reaches Recv, Peers or NextEvent, and the error's text is sent back as the reason. Nil accepts every client.
//
// The WebSocket server calls Verify on the client's own goroutine. The UDP server calls it on its receive goroutine, so a slow Verify delays every UDP peer's packets; check a signed token locally rather than calling a remote service there. The UDP server runs it only for a client that echoed the cookie sent to its address, so datagrams with spoofed source addresses never reach it.
Verify func(peer PeerID, token []byte) error
// GracePeriod is how long a dropped peer keeps its ID and session. A client that reconnects within it resumes with the same ID and NextEvent reports PeerResumed; once it passes, NextEvent reports PeerLeft. Zero reports PeerLeft as soon as the connection drops.
GracePeriod time.Duration
// IdleTimeout is how long a peer may stay silent before the server counts it as dropped; 10 seconds when zero, and a value below 3 seconds is raised to 3 seconds. UDP clients ping every second while idle, so a gap of up to 2 seconds is normal. A WebSocket server pings each client every third of IdleTimeout and drops one that sends no frame, not even the pong, for IdleTimeout, so a client whose network vanished without closing the TCP connection does not keep its session forever. The WebSocket timeout runs on the wall clock, not on Now.
IdleTimeout time.Duration
// MaxPeers is the most sessions the server holds at once, counting peers inside their grace period and handshakes waiting on Verify; 1024 when zero. A client past it is rejected with the reason "server full", so a flood of handshakes cannot grow the server without bound.
MaxPeers int
// Now is the clock for grace periods and idle timeouts; nil uses time.Now.
Now func() time.Time
// StaticKey is the server's static X25519 private key for ListenUDPServer's Noise NK handshake. When nil, ListenUDPServer generates a fresh X25519 key pair (available via UDPServer.PublicKey); set a persistent key when clients know it from configuration rather than a matchmaking ticket, or must reconnect across server restarts. A non-X25519 key makes ListenUDPServer return ErrInvalidKey. Ignored by WebSocket servers, which use TLS.
StaticKey *ecdh.PrivateKey
}Auth configures the connection handshake that ListenWebSocket, ListenWebTransport, and ListenUDPServer run before a peer may send or receive game packets.
The zero value accepts every client, assigns its ID and treats a dropped connection as a leave. A server reachable from the internet should set Verify: without it anyone may join, up to MaxPeers.
type CaptureDirection stringCaptureDirection identifies whether a captured packet was sent or received by the wrapped Transport.
const (
// CaptureSend marks a packet passed to Transport.Send.
CaptureSend CaptureDirection = "send"
// CaptureRecv marks a packet returned by Transport.Recv.
CaptureRecv CaptureDirection = "recv"
)type CaptureOptions struct {
// Channels, when non-empty, restricts capture to packets on one of the listed channels.
Channels []Channel
// Peers, when non-empty, restricts capture to packets sent to or received from one of the listed peers.
Peers []PeerID
// SampleEvery records one out of every N matching packets (0 or 1 records every matching packet).
SampleEvery int
// SampleRate, when in (0, 1) and SampleEvery <= 1, probabilistically records each matching packet using SampleSeed.
SampleRate float64
// SampleSeed seeds the deterministic PRNG used with SampleRate.
SampleSeed int64
// Now returns the clock used to stamp elapsed nanoseconds T since NewCaptureTransport was called; time.Now when nil.
Now func() time.Time
// OnError, when non-nil, is called if encoding or writing a capture line fails. Capture write errors never fail Send or Recv.
OnError func(error)
}CaptureOptions configures filtering, sampling, timing, and error reporting for NewCaptureTransport.
type CaptureRecord struct {
// Version is the capture format version; it must equal CaptureVersion (1).
Version int `json:"version"`
// T is the monotonic elapsed time in nanoseconds since NewCaptureTransport started capturing.
T int64 `json:"t"`
// Dir is "send" for outbound Transport.Send calls or "recv" for inbound Transport.Recv packets.
Dir CaptureDirection `json:"dir"`
// Peer is the destination peer ID (or PeerBroadcast) on send, or Packet.From on recv.
Peer PeerID `json:"peer"`
// Ch is the transport delivery channel (ChannelReliableOrdered or ChannelUnreliable).
Ch Channel `json:"ch"`
// Seq is the transport packet sequence number.
Seq uint32 `json:"seq"`
// Payload is the raw plaintext transport payload bytes, encoded as standard base64 in JSON.
Payload []byte `json:"payload"`
}CaptureRecord is one line of a version 1 packet capture JSONL stream.
Each line is a self-contained UTF-8 JSON object:
{"version":1,"t":0,"dir":"send","peer":2,"ch":0,"seq":1,"payload":"AQID"}
Warning: captured payloads contain plaintext player inputs, entity coordinates, and game state. Treat capture files like player telemetry and never ship or publish them without consent.
func ParseCaptureRecord(line []byte) (CaptureRecord, error)ParseCaptureRecord strictly decodes and validates one JSON line into a CaptureRecord, refusing unknown fields, trailing data, missing or unsupported versions, invalid directions or channels, negative timestamps, and missing or null payloads.
func ReadCapture(r io.Reader) ([]CaptureRecord, error)ReadCapture reads every non-empty JSONL line from r and returns the parsed CaptureRecords in order.
type Channel uint8Channel selects delivery semantics for a packet.
const (
// ChannelReliableOrdered guarantees delivery in send order. A transport that cannot provide that guarantee refuses it with ErrUnsupportedChannel rather than silently dropping packets; UDP has no retransmission, so lockstep and rollback need WebSocket, loopback or a RelayTransport, which retransmits end to end over either protocol.
ChannelReliableOrdered Channel = 0
// ChannelUnreliable delivers best-effort packets that may be dropped or reordered.
ChannelUnreliable Channel = 1
)func (c Channel) String() stringString returns a human-readable channel name.
type ClientWorld struct {
// OnSpawn is invoked when a new entity first appears in an authoritative snapshot.
OnSpawn func(EntityState)
// OnDespawn is invoked when an entity disappears from an authoritative snapshot.
OnDespawn func(EntityID)
// contains filtered or unexported fields
}ClientWorld receives authoritative snapshots from a ServerWorld, maintains a timed snapshot ring buffer for smooth interpolation, fires spawn/despawn hooks, and supports client-side prediction with automatic server reconciliation.
A ClientWorld follows the server's replication epoch. A complete full snapshot of a new epoch means the server restarted: the client forgets every snapshot and prediction of the old epoch as Reset does, reporting each entity it knew through OnDespawn, and continues from the new one without the game calling Reset. A delta of a new epoch only makes the client ask for a full snapshot of it. Late snapshots of an epoch the client has left are ignored, unless that epoch sends 32 snapshots in a row with none of the current epoch between them: then it is the live one, and the client follows it again.
func NewClientWorld(transport Transport, serverID PeerID) *ClientWorldNewClientWorld creates a replication client connected to serverID via transport.
func (c *ClientWorld) Entity(id EntityID) (EntityState, bool)Entity returns the latest authoritative state of id.
func (c *ClientWorld) Epoch() (uint32, bool)Epoch returns the server's replication epoch the client's snapshots belong to, and false before the first snapshot and after Reset.
func (c *ClientWorld) Err() errorErr returns why the server's last replication message could not be used, an error wrapping ErrReplicationVersion when the server speaks another version of the replication protocol, or nil. A game can show it and stop waiting for a world that will never arrive. It clears when a snapshot applies and on Reset.
func (c *ClientWorld) Interpolate(renderTick float64) []EntityStateInterpolate returns a sorted slice of entities interpolated at renderTick across the buffered authoritative snapshots (smoothly lerping X, Y, VX, VY, and shortest-arc Rotation).
renderTick is read relative to the latest snapshot's tick, modulo 2^32, so a render time computed from uint32 ticks keeps working across a tick counter wraparound.
func (c *ClientWorld) LastReconcileError() float32LastReconcileError returns the Euclidean position delta between the predicted state and reconciled state from the most recent reconciliation.
func (c *ClientWorld) LatestTick() (uint32, bool)LatestTick returns the highest authoritative snapshot tick received so far.
func (c *ClientWorld) PendingPredictions(id EntityID) intPendingPredictions returns the number of unacknowledged predicted inputs buffered for id.
func (c *ClientWorld) Poll() intPoll drains all pending snapshots from Transport, updates the ring buffer, triggers OnSpawn/OnDespawn callbacks, sends acknowledgments back to the server, and reconciles locally predicted entities. Returns the number of snapshots applied.
A complete full snapshot of a new epoch makes the client follow the server into it, reporting every entity of the old epoch through OnDespawn first; a delta of a new epoch makes it ask the server for a full snapshot. Snapshots of epochs the client has left are ignored, as described on ClientWorld. A message of another version of the replication protocol sets Err, and the next snapshot that applies clears it.
func (c *ClientWorld) Predict(localEntity EntityID, input any, apply func(*EntityState, any))Predict applies a local input immediately to localEntity and buffers it for reconciliation when authoritative snapshots arrive.
func (c *ClientWorld) PredictedState(id EntityID) (EntityState, bool)PredictedState returns the locally predicted state for id if active, falling back to the latest authoritative state.
func (c *ClientWorld) Reconciliations() intReconciliations returns the total number of client-side prediction reconciliations performed.
func (c *ClientWorld) Reset()Reset forgets every snapshot, partial snapshot and prediction and the server's epoch, as when the client joins a new match, and reports every entity the client knew through OnDespawn, in EntityID order. A restarted ServerWorld sends a new epoch, which the client follows without a Reset; a server that starts its tick count over in the same epoch, without SetEpoch, needs one, because snapshot ticks are compared in serial-number order and the client would drop every new snapshot as stale until the new ticks pass the old ones. The epochs the client has left stay ignored, as long as they send no more than a late burst. Reconciliations and LastReconcileError keep counting.
type ComponentState struct {
Kind uint16
X float32
Y float32
VX float32
VY float32
Rotation float32
Flags uint32
Props []byte
}ComponentState holds the replicated transform, velocity, flags, and custom properties of an entity.
func (c ComponentState) Clone() ComponentStateClone returns a deep copy of ComponentState (duplicating Props).
type ConnState uint8ConnState is a client transport's connection state.
const (
// ConnConnecting is a client whose handshake has not finished.
ConnConnecting ConnState = iota
// ConnOpen is a client the server accepted.
ConnOpen
// ConnDisconnected is a client whose connection dropped or was rejected; Reconnect may resume it.
ConnDisconnected
// ConnClosed is a client closed with Close.
ConnClosed
)type DesyncEvent struct {
Tick uint32
LocalPeer PeerID
RemotePeer PeerID
LocalChecksum uint64
RemoteChecksum uint64
}DesyncEvent describes a detected state checksum divergence between peers.
type EntityID uint32EntityID uniquely identifies a replicated entity in a ServerWorld / ClientWorld.
type EntityState struct {
ID EntityID
ComponentState
}EntityState pairs an EntityID with its replicated ComponentState.
func (e EntityState) Clone() EntityStateClone returns a deep copy of EntityState.
type InboxLimits struct {
// Unreliable is the most ChannelUnreliable packets the inbox holds from one peer. Zero uses DefaultUnreliableInbox; a negative value removes the cap.
Unreliable int
// Reliable is the most ChannelReliableOrdered packets a WebSocketServer's or RelayTransport's inbox holds from one peer. Zero uses DefaultReliableInbox; a negative value removes the cap. The other transports ignore it.
Reliable int
// ReliableWarning is the ChannelReliableOrdered backlog, across all peers, that raises a warning: the warning counts once when the backlog grows past it, and counts again only after the backlog has fallen to half of it, so a queue hovering at the threshold does not raise one warning per packet. Zero uses DefaultReliableInboxWarning; a negative value turns the warning off.
ReliableWarning int
}InboxLimits bounds the packets a transport keeps until Recv takes them. Every transport in this package accepts it through SetInboxLimits, and LoopbackConfig and RelayTransportConfig carry it too.
The unreliable channel is capped per peer: when a ChannelUnreliable packet arrives from a peer that already has Unreliable packets queued, that peer's oldest queued unreliable packet is dropped to make room, so a consumer that falls behind keeps the newest state rather than the stalest, a peer that floods the inbox evicts only its own packets, and InboxStats.UnreliableDropped counts the loss.
The reliable channel is never trimmed, because dropping a packet would break ChannelReliableOrdered. A transport that receives reliable packets from peers it cannot trust caps them per peer at Reliable instead and refuses the packet that goes past it, counting it in InboxStats.ReliableRefused: WebSocketServer then ends that client's session, as if it had left, so the packets it did deliver stay in order, and RelayTransport leaves the message unacknowledged, so the sending peer resends it once Recv has made room. The other transports receive reliable packets only from their server or from the same process and keep them all. Every transport counts a warning in InboxStats.ReliableWarnings when its whole reliable backlog passes ReliableWarning.
type InboxReporter interface {
SetInboxLimits(InboxLimits)
InboxStats() InboxStats
}InboxReporter is implemented by every transport in this package: LoopbackTransport, WebSocketTransport, WebSocketServer, WebTransportTransport, WebTransportServer, UDPTransport, UDPServer, UDPClient and RelayTransport. SetInboxLimits changes the inbox's limits at any time; lowering the unreliable cap below what a peer has queued drops that peer's oldest unreliable packets at once and counts them, and lowering the reliable cap refuses only the packets that arrive afterwards. InboxStats reads the inbox's counters.
type InboxStats struct {
// Unreliable is the number of ChannelUnreliable packets waiting for Recv.
Unreliable int
// Reliable is the number of ChannelReliableOrdered packets waiting for Recv.
Reliable int
// UnreliableDropped counts the unreliable packets dropped because their peer already had InboxLimits.Unreliable packets queued when a newer one arrived.
UnreliableDropped uint64
// ReliableRefused counts the reliable packets a WebSocketServer or RelayTransport refused because their peer already had InboxLimits.Reliable packets queued.
ReliableRefused uint64
// ReliableWarnings counts the times the reliable backlog grew past InboxLimits.ReliableWarning: once per crossing, not once per packet.
ReliableWarnings uint64
// ReliableBacklog is true from the moment the reliable backlog passes InboxLimits.ReliableWarning until it falls to half of it.
ReliableBacklog bool
}InboxStats reports a transport's inbox: what is queued and what the limits did. The counters only grow, so a game or a debug overlay that polls InboxStats every frame reports a warning or a loss when a counter differs from the previous frame's.
type InputFrame struct {
Tick uint32
Peer PeerID
Bits uint64
Axes [2]int16
}InputFrame is a deterministic per-tick player input sample.
type KickError struct {
Reason string
}KickError is the reason a server gave for removing a client's session with WebSocketServer.Kick or UDPServer.Kick.
func (e *KickError) Error() stringError returns the kick with its reason.
func (e *KickError) Is(target error) boolIs reports whether target is ErrKicked.
type LockstepConfig struct {
Transport Transport
Sim SimState
Peers []PeerID
ChecksumInterval int
OnDesync func(DesyncEvent)
// Host is the peer that admits and removes peers while the match runs, with AddPeer and RemovePeer. Zero means the lowest ID of Peers, leaving out the local peer when Join is set; a joining session that finds no other peer there, or that names itself, takes the lowest other ID the transport reports on each Poll until its join state arrives. Set it explicitly when joining over a relay, whose peer list may still be empty or include other newcomers. Every peer of a match must name the same host, and the host stays for the whole match.
Host PeerID
// Join starts the session as a peer joining a match already running. It takes no part until the host's join state arrives with the tick it joins at, the peers and the simulation's state, which it loads into Sim; until then Step does nothing and Active reports false. Peers then only serves to find the host when Host is zero.
Join bool
}LockstepConfig configures a strict deterministic LockstepSession.
type LockstepSession struct {
// contains filtered or unexported fields
}LockstepSession advances a deterministic simulation tick only once every participating peer's input for that tick has arrived, exchanging periodic state checksums to detect desyncs.
Peers may join and leave while the match runs: the host admits one with AddPeer and removes one with RemovePeer, and every peer applies the change at the same tick.
func NewLockstepSession(cfg LockstepConfig) *LockstepSessionNewLockstepSession creates a strict lockstep session.
func (s *LockstepSession) Active() boolActive reports whether the local peer takes part in the current tick: false while a joining peer waits for its join state, and from the tick the host removed the local peer at.
func (s *LockstepSession) AddPeer(id PeerID) (uint32, error)AddPeer admits a peer to the running match and returns the tick it joins at. Only the host may call it, typically when its transport reports the peer (PeerJoined, or a new member in a RelayTransport's Peers). The tick is the host's next own input tick, so no peer has run it yet; the other peers learn of the change before the host's input for that tick, and inputs before it are not expected from the new peer. Once the host's simulation stands at the start of the join tick, Step sends the new peer the state, which must be no larger than MaxJoinStateSize, the tick and the peers.
Adding a peer that already takes part returns its join tick. It returns ErrNotHost on any other peer, ErrPeerRejoin for a peer that has left, ErrUnknownPeer for ID 0 and ErrPayloadTooLarge when the state is larger than MaxJoinStateSize.
func (s *LockstepSession) Desyncs() []DesyncEventDesyncs returns a copy of the most recent DesyncEvents observed, up to maxDesyncHistory of them; OnDesync still sees every one.
func (s *LockstepSession) Members() []PeerIDMembers returns the sorted IDs of the peers taking part in the current tick; it is empty while a joining peer waits for its join state.
func (s *LockstepSession) Poll()Poll drains all pending input, checksum and membership messages from the Transport, first sending again the messages kept for peers the transport could not reach.
func (s *LockstepSession) RemovePeer(id PeerID) (uint32, error)RemovePeer removes a peer from the running match and returns the tick from which no peer waits for it. Only the host may call it, typically once its transport reports the peer gone (PeerLeft, or a RelayTransport's Peers no longer listing it). The tick is the host's next own input tick or the peer's join tick, whichever is later. The change carries the inputs the host holds from the peer for the ticks before it and a zero input for each tick the host never received, so every peer runs those ticks alike; a peer still sending when removed may have reached another peer with an input the host never saw, so remove a peer after it has stopped sending.
Removing a peer that is already leaving, or that left, returns its leave tick. It returns ErrNotHost on any other peer, ErrHostLeave for the host and ErrUnknownPeer for a peer not in the match.
func (s *LockstepSession) Step() boolStep polls incoming packets and advances the simulation by one tick if every peer's input for the current tick is present. Returns true when a tick executed.
func (s *LockstepSession) SubmitInput(in InputFrame) errorSubmitInput records the local peer's input for in.Tick and sends it to every other peer taking part in that tick. An input for a tick already run or more than 256 ticks ahead, or for a tick the local peer takes no part in, is ignored, as is any input once the host has removed the local peer: the host's leave change carries the inputs every peer uses. A send the transport cannot make right now, to a peer that is reconnecting or that a relay has not announced yet, is kept and retried by Poll; once too many wait for one peer, SubmitInput returns ErrSessionBacklog.
func (s *LockstepSession) Tick() uint32Tick returns the number of ticks simulated so far (also the next tick to execute). A joining peer's count starts at its join tick.
type LoopbackConfig struct {
// Latency is the base one-way packet transit delay.
Latency time.Duration
// Jitter adds a uniform random offset in [-Jitter, +Jitter] to Latency (clamped to >= 0).
Jitter time.Duration
// LossRate is the drop probability in [0, 1] applied to ChannelUnreliable packets only.
// ChannelReliableOrdered packets are never dropped and always arrive in send order.
LossRate float64
// Seed initializes the deterministic PRNG used for jitter and packet loss.
Seed int64
// Inbox bounds the inbox of each peer AddPeer adds from then on (see InboxLimits); the zero value uses the defaults. SetConfig leaves it unchanged; LoopbackTransport.SetInboxLimits changes one peer's.
Inbox InboxLimits
}LoopbackConfig configures deterministic network simulation on a LoopbackHub.
type LoopbackHub struct {
// contains filtered or unexported fields
}LoopbackHub simulates an in-memory packet network between LoopbackTransport peers driven by a manual virtual clock via Advance.
func NewLoopbackHub(cfg LoopbackConfig) *LoopbackHubNewLoopbackHub creates a new deterministic in-memory network hub.
func (h *LoopbackHub) AddPeer(id PeerID) *LoopbackTransportAddPeer registers a peer with the given ID and returns its Transport. If a peer with the same ID already exists, it is replaced.
func (h *LoopbackHub) Advance(dt time.Duration)Advance moves the virtual clock forward by dt and delivers all in-flight packets whose scheduled arrival time is <= Now().
func (h *LoopbackHub) Config() LoopbackConfigConfig returns the current network simulation configuration.
func (h *LoopbackHub) InFlight() intInFlight returns the number of packets currently in transit.
func (h *LoopbackHub) Now() time.DurationNow returns the hub's current virtual clock time.
func (h *LoopbackHub) RemovePeer(id PeerID)RemovePeer disconnects a peer from the hub.
func (h *LoopbackHub) SetConfig(cfg LoopbackConfig)SetConfig updates Latency, Jitter, and LossRate at runtime without resetting the PRNG or clock.
type LoopbackTransport struct {
// contains filtered or unexported fields
}LoopbackTransport is an endpoint connected to a LoopbackHub.
func (t *LoopbackTransport) Close() errorClose disconnects this endpoint from its LoopbackHub.
func (t *LoopbackTransport) InboxStats() InboxStatsInboxStats reports what the transport's inbox holds and what its limits dropped or warned about.
func (t *LoopbackTransport) LocalID() PeerIDLocalID returns this endpoint's PeerID.
func (t *LoopbackTransport) Peers() []PeerIDPeers returns the sorted list of other connected peers on the hub.
func (t *LoopbackTransport) Recv() (Packet, bool)Recv pops the next delivered packet without blocking.
func (t *LoopbackTransport) Send(to PeerID, ch Channel, payload []byte) errorSend transmits payload to the target peer (or all other peers if to == PeerBroadcast).
func (t *LoopbackTransport) SetInboxLimits(l InboxLimits)SetInboxLimits bounds the packets the transport keeps until Recv takes them (see InboxLimits).
type OutboxLimits struct {
// Frames is the most frames one client's outbox holds. Zero uses DefaultOutboxFrames; a negative value removes the cap.
Frames int
// Bytes is the most bytes of frames one client's outbox holds, counting each frame's payload and its 5-byte header. Zero uses DefaultOutboxBytes; a negative value removes the cap.
Bytes int
}OutboxLimits bounds the frames a WebSocketServer or WebTransportServer holds for one client before they are written to its connection.
Send never writes to a client's connection itself: it queues the frame in the client's outbox and returns, and a goroutine of the client's own writes the queue out, so a client that reads slowly, or stops reading, delays only its own frames and never the caller's tick or the other clients. A WebTransportServer gives each client a second outbox, with the same limits, for its ChannelUnreliable datagrams, which QUIC sends apart from the reliable stream. A frame that would take a client's outbox past Frames frames or Bytes bytes first makes room by dropping that client's oldest queued ChannelUnreliable frames. A ChannelUnreliable frame that still does not fit is dropped itself, and a ChannelReliableOrdered frame that does not fit ends the client's session: dropping it would break the channel's order, so NextEvent reports PeerLeft with the reason "outbox full" and Send returns ErrDisconnected for that client. A frame always fits an empty outbox, whatever its size.
Send therefore reports only what it knows when it queues: ErrDisconnected, ErrUnknownPeer, ErrPayloadTooLarge and ErrClosed. A write that fails, or that takes longer than the write timeout (10 seconds), closes the client's connection rather than leave part of a frame on the wire, and NextEvent reports PeerDropped as for any lost connection; the frames still queued for it are discarded.
WebSocketServer.Kick and Close let each client's writer flush the frames already queued for it before the close frame, for at most a second, and cut off the connection of a client that has not taken them by then.
type OutboxReporter interface {
SetOutboxLimits(OutboxLimits)
OutboxStats() OutboxStats
}OutboxReporter is implemented by the server transports that queue each client's outgoing frames: WebSocketServer and WebTransportServer. SetOutboxLimits changes the limits at any time; frames already queued stay, and the new limits apply to the frames Send queues afterwards. OutboxStats reads the outboxes' counters.
type OutboxStats struct {
// Frames is the number of frames queued across every connected client's outbox.
Frames int
// Bytes is the number of bytes those frames hold.
Bytes int
// UnreliableDropped counts the ChannelUnreliable frames dropped because their client's outbox was full.
UnreliableDropped uint64
// Overflows counts the sessions ended because a ChannelReliableOrdered frame did not fit its client's outbox.
Overflows uint64
}OutboxStats reports what a server transport's outboxes hold and what their limits dropped.
type Packet struct {
From PeerID
Channel Channel
Payload []byte
Seq uint32
}Packet is a single datagram received from a remote peer.
type PeerEvent struct {
Kind PeerEventKind
Peer PeerID
// Reason is why a server removed the peer: the reason given to WebSocketServer.Kick or UDPServer.Kick, or "outbox full" when a WebSocketServer or WebTransportServer ended the session because the client's reliable frames no longer fit its outbox (see OutboxLimits). It is empty for every other event.
Reason string
}PeerEvent is one change to a peer's session, reported by a server's NextEvent.
type PeerEventKind uint8PeerEventKind is what happened to a peer's session.
const (
// PeerJoined reports a client that passed the handshake and received a new ID.
PeerJoined PeerEventKind = iota + 1
// PeerDropped reports a connection that broke without a goodbye; the peer keeps its ID for Auth.GracePeriod.
PeerDropped
// PeerResumed reports a dropped peer that reconnected within the grace period with its old ID.
PeerResumed
// PeerLeft reports a peer that closed its connection, or whose grace period ran out. Its ID is gone.
PeerLeft
)func (k PeerEventKind) String() stringString returns the event kind's name.
type PeerEvents interface {
NextEvent() (PeerEvent, bool)
}PeerEvents is implemented by the server transports that run the connection handshake. NextEvent pops the next session change without blocking; grace periods and idle timeouts are checked when it is called, so a server polls it every tick alongside Recv.
type PeerID uint32PeerID uniquely identifies a participant in a multiplayer session.
const PeerBroadcast PeerID = 0PeerBroadcast targets all connected remote peers when passed to Transport.Send.
type RejectError struct {
Reason string
}RejectError is the reason a server gave for refusing a client's handshake.
func (e *RejectError) Error() stringError returns the rejection with its reason.
func (e *RejectError) Is(target error) boolIs reports whether target is ErrRejected.
type Relay struct {
// contains filtered or unexported fields
}Relay forwards packets between the peers of a peer-to-peer session, so lockstep and rollback work for players who cannot reach each other directly: each player connects to the relay with a RelayTransport over WebSocket or UDP, and the relay passes each frame to the member it is addressed to.
The relay sits on a WebSocketServer or UDPServer, so every client passes that server's connection handshake first; Join then decides which session the client belongs to. A frame addressed outside the sender's session is dropped. The relay never reads the payloads, and reliability is end to end between RelayTransports, so the relay may drop a frame for a member that is reconnecting or too slow without breaking ChannelReliableOrdered.
func NewRelay(cfg RelayConfig) (*Relay, error)NewRelay returns a relay for cfg. It fails when cfg.Join is nil.
func (r *Relay) Auth(base Auth) AuthAuth returns base with Verify replaced by the relay's admission: base.Verify, when set, checks the token first, then Join picks the session and the relay refuses a full one. Pass the result to ListenWebSocket, ListenWebSocketTLS or ListenUDPServer, and serve that server with Serve.
func (r *Relay) Serve(ctx context.Context, srv RelayServer) errorServe forwards srv's packets until ctx ends, then stops the members' writers and returns ctx's error. srv must have been created with r.Auth. A relay serves one server for its lifetime: Serve may be called again on the same server after it returns, and the clients still connected keep their sessions, but a concurrent Serve or a Serve on another server returns an error. Serve does not close srv.
func (r *Relay) Stats() RelayStatsStats returns the relay's current counts.
type RelayConfig struct {
// Join admits a client to a session: it checks the token the client presented in the connection handshake and returns the name of the session the client joins, or an error whose text is sent back as the rejection reason. Packets are forwarded only between members of the same session. Join is required. It runs where Auth.Verify runs: on the client's goroutine for WebSocket and on the receive goroutine for UDP, so check a signed token locally.
Join func(peer PeerID, token []byte) (session string, err error)
// MaxSessionPeers is the most members a session holds, counting members inside their grace period; 8 when zero. A client past it is rejected with the reason "session full".
MaxSessionPeers int
// QueueSize is how many frames the relay holds for one member that has not been written yet; 256 when zero. Frames past it are dropped, and the senders' RelayTransports resend the reliable ones.
QueueSize int
}RelayConfig configures a Relay.
type RelayServer interface {
Transport
PeerEvents
}RelayServer is a server transport a Relay serves: WebSocketServer, WebTransportServer, or UDPServer.
type RelayStats struct {
// Sessions is the number of sessions with at least one member.
Sessions int
// Peers is the number of members across all sessions, including members inside their grace period.
Peers int
// Forwarded counts frames queued for a member, including the relay's own membership updates.
Forwarded uint64
// Dropped counts frames refused: malformed, from a client in no session, addressed outside the sender's session, or past a member's queue.
Dropped uint64
}RelayStats counts a relay's sessions and traffic.
type RelayTransport struct {
// contains filtered or unexported fields
}RelayTransport is a peer-to-peer Transport whose packets travel through a Relay, so peers that cannot reach each other, behind NAT or in a browser, still exchange packets. It wraps a client transport connected to the relay: a WebSocketTransport (native or browser), a WebTransportTransport (native or browser), or a UDPClient.
Peers reports the other members of the relay session the client joined, and Send addresses them by the IDs the relay assigned. ChannelReliableOrdered is reliable and ordered end to end: the transport numbers each peer's messages, the receiver acknowledges them, and lost ones are sent again, so it works over UDP, which drops datagrams, and survives the relay dropping a packet for a peer that is reconnecting. ChannelUnreliable packets are sent once and may be lost.
Acknowledgements and retransmissions happen inside Recv, so a game polls Recv every tick, as LockstepSession and RollbackSession do.
func NewRelayTransport(inner Transport, cfg RelayTransportConfig) *RelayTransportNewRelayTransport wraps inner, a client transport whose handshake with a Relay has succeeded. Closing the RelayTransport closes inner. To reconnect after a drop, call the inner transport's Reconnect: within the relay's grace period the client keeps its ID and its messages, and unacknowledged reliable ones are sent again.
func (rt *RelayTransport) Close() errorClose closes the inner transport.
func (rt *RelayTransport) InboxStats() InboxStatsInboxStats reports what the transport's inbox holds and what its limits dropped or warned about.
func (rt *RelayTransport) LocalID() PeerIDLocalID returns the ID the relay assigned this client.
func (rt *RelayTransport) Peers() []PeerIDPeers returns the sorted IDs of the other members of this client's relay session, including members inside the relay's grace period, as of the last membership update Recv processed.
func (rt *RelayTransport) Recv() (Packet, bool)Recv pops the next packet from a session member without blocking. Each call first drains the inner transport, acknowledges reliable messages and resends the ones whose acknowledgement is overdue.
func (rt *RelayTransport) Send(to PeerID, ch Channel, payload []byte) errorSend sends payload to a member of the session, or to every other member when to is PeerBroadcast. It returns ErrUnknownPeer for an ID outside the session, ErrPayloadTooLarge above MaxRelayPayload and ErrRelayBacklog when a peer has too many unacknowledged reliable messages. A reliable message the inner transport cannot send right now, because it is reconnecting, is kept and sent again; an unreliable one returns the inner transport's error.
func (rt *RelayTransport) SetInboxLimits(l InboxLimits)SetInboxLimits bounds the packets the transport keeps until Recv takes them (see InboxLimits). A peer whose queued reliable messages reach InboxLimits.Reliable is not acknowledged further, so it resends them once Recv has made room.
type RelayTransportConfig struct {
// Now is the clock for retransmission timers; nil uses time.Now.
Now func() time.Time
// Inbox bounds the packets the RelayTransport keeps until Recv takes them (see InboxLimits); the zero value uses the defaults. The inner transport's inbox has its own limits, set on it directly; the relay carries reliable messages as unreliable frames, so a frame the inner inbox drops is sent again.
Inbox InboxLimits
}RelayTransportConfig configures a RelayTransport.
type ReplicationStats struct {
BytesSent uint64
PacketsSent uint64
SnapshotsSent uint64
FullSnapshotsSent uint64
DeltaSnapshotsSent uint64
AvgBytesPerTick float64
}ReplicationStats reports cumulative bandwidth and snapshot metrics for ServerWorld.
type RollbackConfig struct {
Transport Transport
Sim SimState
Peers []PeerID
MaxRollback int
InputDelay int
ChecksumInterval int
OnDesync func(DesyncEvent)
// Host is the peer that admits and removes peers while the match runs, with AddPeer and RemovePeer. Zero means the lowest ID of Peers, leaving out the local peer when Join is set; a joining session that finds no other peer there, or that names itself, takes the lowest other ID the transport reports on each Poll until its join state arrives. Set it explicitly when joining over a relay, whose peer list may still be empty or include other newcomers. Every peer of a match must name the same host, and the host stays for the whole match.
Host PeerID
// Join starts the session as a peer joining a match already running. It takes no part until the host's join state arrives with the tick it joins at, the peers and the simulation's state, which it loads into Sim; until then Step only polls and Active reports false. Peers then only serves to find the host when Host is zero.
Join bool
}RollbackConfig configures a GGPO-style RollbackSession.
type RollbackSession struct {
// contains filtered or unexported fields
}RollbackSession runs a GGPO-style optimistic deterministic simulation: missing remote inputs are predicted by repeating the last confirmed input, pre-step snapshots are kept in a ring window, late divergent inputs trigger rollback + deterministic re-simulation, and confirmed ticks exchange periodic state checksums for immediate desync detection.
Peers may join and leave while the match runs: the host admits one with AddPeer and removes one with RemovePeer, and every peer applies the change at the same tick, rolling back when it has already simulated past it.
func NewRollbackSession(cfg RollbackConfig) *RollbackSessionNewRollbackSession creates a GGPO-style rollback session.
func (s *RollbackSession) Active() boolActive reports whether the local peer takes part in the current tick: false while a joining peer waits for its join state, and from the tick the host removed the local peer at.
func (s *RollbackSession) AddPeer(id PeerID) (uint32, error)AddPeer admits a peer to the running match and returns the tick it joins at. Only the host may call it, typically when its transport reports the peer (PeerJoined, or a new member in a RelayTransport's Peers). The tick is the one the host's next local input applies to (Tick plus InputDelay), so no peer has confirmed it yet; a peer that has already simulated past it rolls back. The new peer's inputs for its first InputDelay ticks are zero on every peer. Once the host has confirmed every tick before the join tick, it sends the new peer the state at the start of that tick, which must be no larger than MaxJoinStateSize, the tick and the peers.
Adding a peer that already takes part returns its join tick. It returns ErrNotHost on any other peer, ErrPeerRejoin for a peer that has left, ErrUnknownPeer for ID 0 and ErrPayloadTooLarge when the state is larger than MaxJoinStateSize.
func (s *RollbackSession) ConfirmedTick() int64ConfirmedTick returns the highest tick for which all peers' inputs are confirmed, or -1 if no tick is fully confirmed yet.
func (s *RollbackSession) Desyncs() []DesyncEventDesyncs returns a copy of the most recent DesyncEvents detected, up to maxDesyncHistory of them; OnDesync and Stats().Desyncs still count every one.
func (s *RollbackSession) Members() []PeerIDMembers returns the sorted IDs of the peers taking part in the current tick; it is empty while a joining peer waits for its join state.
func (s *RollbackSession) Poll() errorPoll drains incoming remote inputs, checksums and membership messages from the Transport, rolling back and re-simulating if any late remote input or membership change diverges from what was previously simulated. It first sends again the messages kept for peers the transport could not reach, and returns ErrSessionBacklog once for a peer that more such messages wait for than a session keeps: that peer misses the messages sent to it from then on.
func (s *RollbackSession) RemovePeer(id PeerID) (uint32, error)RemovePeer removes a peer from the running match and returns the tick from which no peer waits for or predicts it. Only the host may call it, typically once its transport reports the peer gone (PeerLeft, or a RelayTransport's Peers no longer listing it). The tick is the one the host's next local input applies to, or the peer's join tick, whichever is later. The change carries the inputs the host holds from the peer and a zero input for each unconfirmed tick the host never received, so every peer confirms those ticks alike, rolling back where it predicted otherwise; a peer still sending when removed may have reached another peer with an input the host never saw, so remove a peer after it has stopped sending.
Removing a peer that is already leaving, or that left, returns its leave tick. It returns ErrNotHost on any other peer, ErrHostLeave for the host, ErrUnknownPeer for a peer not in the match, and ErrRollbackWindowExceeded when the host would have to roll back further than MaxRollback or the change would carry more inputs than fit one message.
func (s *RollbackSession) Stats() RollbackStatsStats returns a snapshot of the rollback session's metrics.
func (s *RollbackSession) Step(localInput InputFrame) errorStep submits the local input (applied at currentTick + InputDelay), drains incoming packets (executing any needed rollbacks), simulates the next tick, and exchanges checksums for newly confirmed ticks. While the local peer takes no part (see Active) it only polls. While the oldest unconfirmed tick is MaxRollback ticks back it only polls too, ignoring localInput, and returns ErrRollbackStalled, naming each peer the tick waits for (see Waiting), until the missing inputs arrive or the host removes those peers. It returns ErrSessionBacklog, after simulating the tick or instead of ErrRollbackStalled, when a remote peer has become unreachable for too long (see Poll).
func (s *RollbackSession) Tick() uint32Tick returns the current simulation tick (number of ticks executed so far). A joining peer's count starts at its join tick.
func (s *RollbackSession) Waiting() []PeerIDWaiting returns the sorted IDs of the remote peers whose input the oldest unconfirmed tick still waits for. While Step returns ErrRollbackStalled these are the peers holding the match; one that stays there, having stopped sending or become unreachable, is for the host to remove with RemovePeer.
type RollbackStats struct {
Rollbacks int
MaxRollbackDepth int
ResimulatedFrames int
Predictions int
Mispredictions int
Desyncs int
}RollbackStats tracks runtime rollback and prediction metrics.
type ServerWorld struct {
// contains filtered or unexported fields
}ServerWorld owns authoritative entity state and replicates compact full and bitmask-delta snapshots to connected peers over a Transport.
Every snapshot carries the server's replication epoch, a number NewServerWorld picks at random, so a ClientWorld notices that a restarted server's snapshots come from a new run and starts over on its own.
func NewServerWorld(transport Transport) *ServerWorldNewServerWorld creates a new authoritative replication world backed by transport, with a random replication epoch. Two runs pick the same epoch with a chance of one in 2^32; SetEpoch takes a number the game chooses instead.
func (w *ServerWorld) Despawn(id EntityID) boolDespawn removes an entity from the authoritative world. Returns false if id does not exist.
func (w *ServerWorld) Entities() []EntityStateEntities returns all active entities sorted by EntityID.
func (w *ServerWorld) Entity(id EntityID) (EntityState, bool)Entity returns a copy of the authoritative state for id.
func (w *ServerWorld) Epoch() uint32Epoch returns the replication epoch every snapshot of this world carries.
func (w *ServerWorld) PeerErr(peer PeerID) errorPeerErr returns why the last replication message from peer could not be used, an error wrapping ErrReplicationVersion when the peer speaks another version of the replication protocol, or nil. A server can drop such a peer with a message to update the game. It clears when the peer sends a message of ReplicationVersion, and is forgotten when the peer disconnects.
func (w *ServerWorld) SetEpoch(epoch uint32)SetEpoch replaces the replication epoch, for a server that keeps its own run counter or starts a new match with its tick count back at zero. Clients drop every snapshot and prediction of the old epoch and resync from a full snapshot of the new one, which SetEpoch makes the next Step send to every peer by forgetting the snapshot history and acknowledgments. A client ignores late snapshots of the epochs it has left, so an epoch must not repeat: setting one a client has already left makes that client ignore the server. Setting the current epoch does nothing.
func (w *ServerWorld) SetMaxSnapshotSize(n int)SetMaxSnapshotSize sets the largest payload Step passes to Transport.Send. A full snapshot larger than n is split into parts of at most n bytes, which ClientWorld reassembles before applying, and a delta larger than n is replaced by a full snapshot split the same way. Without the split, a world that outgrew the transport's packet limit could never reach a new peer again (#546). Zero restores DefaultMaxSnapshotSize, and a value below 256 is raised to 256.
func (w *ServerWorld) Spawn(state EntityState) EntityIDSpawn creates a new entity with the given initial state and returns its assigned EntityID.
func (w *ServerWorld) Stats() ReplicationStatsStats returns cumulative replication bandwidth and snapshot statistics.
func (w *ServerWorld) Step(tick uint32) errorStep processes incoming client acknowledgments, records the world snapshot for tick, and transmits either a full snapshot (for new peers) or a bitmask delta snapshot (for acknowledged peers) over the Transport.
func (w *ServerWorld) Update(id EntityID, state EntityState) boolUpdate replaces the state of an existing entity. Returns false if id does not exist.
type SimState interface {
// Step advances the simulation by one fixed tick using inputs sorted by PeerID.
Step(inputs []InputFrame)
// Save serializes the complete deterministic simulation state.
Save() []byte
// Load restores the complete simulation state from a snapshot returned by Save.
Load(snapshot []byte) error
// Checksum returns a deterministic 64-bit hash of the current simulation state.
Checksum() uint64
}SimState is the deterministic simulation interface driven by LockstepSession and RollbackSession.
type Transport interface {
Send(to PeerID, ch Channel, payload []byte) error
Recv() (Packet, bool)
LocalID() PeerID
Peers() []PeerID
Close() error
}Transport is the cross-target messaging interface consumed by replication and lockstep/rollback sessions.
Recv is strictly non-blocking so games can drain incoming packets directly inside a fixed-step game.Loop Update callback without stalling a frame.
A transport has a single consumer. Recv hands each packet to exactly one caller, and the consumers in this package (ServerWorld, ClientWorld, LockstepSession, RollbackSession, Relay and RelayTransport) drain every packet waiting on the transport and discard the ones that are not theirs. Two of them reading the same transport therefore steal each other's packets. To run replication and a lockstep or rollback session side by side, give each its own transport, or put a demultiplexer in front that implements Transport for each consumer.
Every transport in this package bounds its inbox and reports on it through InboxReporter: a peer's unreliable packets past a cap are dropped oldest first, a WebSocketServer ends the session of a client whose reliable packets pass a cap, and a reliable backlog past a threshold is counted as a warning (see InboxLimits).
func DialWebTransportWithFallback(wtURL, wsURL string, token []byte, opts WebTransportOptions) (Transport, error)DialWebTransportWithFallback dials rawURL over WebTransport and falls back to DialWebSocket(wsURL, token) when WebTransport cannot connect. Handshake rejections (ErrRejected) and ErrTokenTooLarge are returned directly without falling back.
func NewCaptureTransport(inner Transport, w io.Writer, opts CaptureOptions) TransportNewCaptureTransport wraps inner and writes one JSON Lines CaptureRecord to w for every successful Send and every packet returned by Recv that matches opts.
Because it sits at the Transport boundary, wrapping UDPClient or UDPServer captures plaintext packets above authentication and encryption, so captures never need session keys.
The returned Transport also implements InboxReporter by forwarding SetInboxLimits and InboxStats to inner when inner implements InboxReporter.
Warning: captures contain raw player inputs and game state.
type UDPClient struct {
// contains filtered or unexported fields
}UDPClient is a native UDP Transport connected to a UDPServer. DialUDP authenticates the server and derives directional ChaCha20-Poly1305 session keys using a Noise NK handshake against the server's static X25519 public key. The client pings the server while idle and reports itself disconnected when the server stays silent for 10 seconds; Reconnect runs a fresh Noise NK handshake to rekey the session and resume with the same ID within the server's grace period.
func DialUDP(addr string, serverKey *ecdh.PublicKey, token []byte) (*UDPClient, error)DialUDP connects to the UDPServer at addr, authenticates it with its static X25519 public key serverKey using Noise NK, presents token encrypted in the handshake, and returns once the server accepts it. The server assigns the client's ID, which LocalID reports. A missing or non-X25519 serverKey returns ErrInvalidKey; a refusal returns a *RejectError that matches ErrRejected.
func (c *UDPClient) Close() errorClose sends the server an authenticated goodbye, so it reports PeerLeft at once rather than holding the session for a reconnect, and closes the socket.
func (c *UDPClient) Err() errorErr returns why the client is disconnected: a *RejectError, a handshake timeout, or ErrDisconnected wrapping the cause. It is nil while the connection is open.
func (c *UDPClient) InboxStats() InboxStatsInboxStats reports what the client's inbox holds and what its limits dropped or warned about.
func (c *UDPClient) LocalID() PeerIDLocalID returns the PeerID the server assigned this client.
func (c *UDPClient) Peers() []PeerIDPeers returns the server's PeerID, or nil while disconnected or closed.
func (c *UDPClient) Reconnect() errorReconnect drops the current socket without a goodbye, opens a new one and runs a fresh Noise NK handshake to rekey the session and reset sequence numbers: within the server's grace period the client keeps its ID, and Resumed reports true. Past it, the server admits the client as a new peer when its token is still valid, and LocalID changes.
func (c *UDPClient) Recv() (Packet, bool)Recv pops the next authenticated and decrypted packet from the server without blocking.
func (c *UDPClient) Resumed() boolResumed reports whether the last handshake resumed an existing session, keeping the client's ID.
func (c *UDPClient) Send(to PeerID, ch Channel, payload []byte) errorSend encrypts and authenticates payload with the client-to-server ChaCha20-Poly1305 key and sends it to the server in one datagram. It refuses ChannelReliableOrdered with ErrUnsupportedChannel, returns ErrDisconnected while the connection is down, and returns ErrSequenceExhausted once the 32-bit sequence counter would wrap (call Reconnect to rekey).
func (c *UDPClient) SetInboxLimits(l InboxLimits)SetInboxLimits bounds the packets the client keeps until Recv takes them (see InboxLimits).
func (c *UDPClient) State() ConnStateState returns the connection state.
type UDPServer struct {
// contains filtered or unexported fields
}UDPServer is a native UDP Transport for a server whose clients connect with DialUDP. Each client first echoes a stateless cookie the server sent to its address, proving it receives there, and then runs a Noise NK key exchange (handshake version 3) against the server's static X25519 key before its packets reach Recv; a hello without a valid cookie gets only the cookie, smaller than the hello, and takes no session slot and no Auth.Verify call. Then the token and resume secret travel encrypted, Auth.Verify checks the token, and the server assigns the client's ID in an encrypted welcome.
After the handshake every datagram is encrypted and authenticated with ChaCha20-Poly1305 using directional keys from the Noise split, a 10-byte cleartext header authenticated as associated data, an implicit direction||peer||seq nonce, and a 64-entry replay window that also refuses wrapped sequence numbers. A datagram from another address, with a bad tag, reflected from the opposite direction, or replayed is dropped.
UDP has no connection, so a client that stays silent for Auth.IdleTimeout counts as dropped; DialUDP clients ping every second while idle.
func ListenUDPServer(addr string, serverID PeerID, auth Auth) (*UDPServer, error)ListenUDPServer binds a UDP socket on addr for a server with ID serverID (1 when zero) and starts accepting DialUDP clients under auth. If auth.StaticKey is nil, ListenUDPServer generates a fresh X25519 key pair whose public key clients obtain from PublicKey; otherwise auth.StaticKey must use X25519 or ListenUDPServer returns ErrInvalidKey.
func (s *UDPServer) Addr() stdnet.AddrAddr returns the local bound UDP address.
func (s *UDPServer) Close() errorClose closes the UDP socket.
func (s *UDPServer) Err() errorErr returns why the server stopped receiving: ErrReceiveFailed wrapping the socket's error. Send returns the same error from then on, and clients time out as their datagrams go unread, so a game should close the server and listen again. It is nil while the server receives, and after Close. Errors about a single datagram, such as an ICMP port unreachable for an earlier send, do not stop it.
func (s *UDPServer) InboxStats() InboxStatsInboxStats reports what the server's inbox holds and what its limits dropped or warned about.
func (s *UDPServer) Kick(peer PeerID, reason string) errorKick ends peer's session now: a connected client receives the reason in an encrypted kick datagram, sent udpKickCopies times since UDP may drop it, and the session's resume secret is gone, so the client's Reconnect cannot resume it and joins as a new peer only if Auth.Verify accepts its token again. NextEvent reports PeerLeft with the reason. It returns ErrUnknownPeer for an ID with no session (including a handshake still in Verify) and ErrClosed once the server is closed. A peer inside its grace period gets no datagram; its next datagram simply finds no session.
func (s *UDPServer) LocalID() PeerIDLocalID returns the server's PeerID.
func (s *UDPServer) NextEvent() (PeerEvent, bool)NextEvent pops the next join, drop, resume or leave without blocking, after dropping clients silent for Auth.IdleTimeout and ending sessions whose grace period has passed.
func (s *UDPServer) Peers() []PeerIDPeers returns the sorted IDs of connected clients. Clients inside their grace period are left out.
func (s *UDPServer) PublicKey() *ecdh.PublicKeyPublicKey returns the server's static X25519 public key that clients pass to DialUDP.
func (s *UDPServer) Recv() (Packet, bool)Recv pops the next authenticated and decrypted packet without blocking.
func (s *UDPServer) Send(to PeerID, ch Channel, payload []byte) errorSend encrypts and authenticates payload with the client's server-to-client ChaCha20-Poly1305 key and sends it in one datagram to the client (or all connected clients when to == PeerBroadcast). It refuses ChannelReliableOrdered with ErrUnsupportedChannel, returns ErrDisconnected for a client inside its grace period, ErrUnknownPeer for an ID with no session, and ErrSequenceExhausted if the session's 32-bit sequence counter would wrap.
func (s *UDPServer) SetInboxLimits(l InboxLimits)SetInboxLimits bounds the packets the server keeps until Recv takes them (see InboxLimits).
type UDPTransport struct {
// contains filtered or unexported fields
}UDPTransport is an unreliable/sequenced native UDP Transport between peers that know each other's addresses in advance.
Peers registered with AddPeer use an unauthenticated 9-byte cleartext header (from PeerID + channel + sequence number) suited only for trusted LAN use and tests: a datagram is accepted if its source address matches the address registered for the PeerID it claims, which does not protect against IP spoofing or on-path observers.
Peers registered with AddPeerKey share a 32-byte pre-shared key and use the same ChaCha20-Poly1305 AEAD framing, 10-byte associated-data header, implicit nonce, 64-entry replay window and sequence-wrap refusal as UDPServer and UDPClient. A server whose clients are not known in advance uses ListenUDPServer and DialUDP, which run a Noise NK key exchange per session.
func ListenUDP(addr string, localID PeerID) (*UDPTransport, error)ListenUDP binds a UDP socket on addr for localID and starts receiving datagrams.
func (u *UDPTransport) AddPeer(id PeerID, addr string) errorAddPeer registers or updates a remote peer's UDP address without cryptography (unauthenticated, for LAN use and tests). Datagrams claiming to be from id are accepted only from this address. Use AddPeerKey for authenticated encryption between peers with a pre-shared key.
func (u *UDPTransport) AddPeerKey(id PeerID, addr string, key [32]byte) errorAddPeerKey registers or updates a remote peer's UDP address with a 32-byte pre-shared ChaCha20-Poly1305 key. Datagrams exchanged with id use the same 26-byte AEAD framing, replay window, reflection protection and sequence-wrap refusal as UDPServer and UDPClient, and plaintext datagrams claiming to be from id are dropped. Calling AddPeerKey again resets the peer's sequence counter and replay window, allowing callers to rekey with a fresh key. An all-zero key returns ErrInvalidKey; id == 0 or id == LocalID returns ErrInvalidPacket.
func (u *UDPTransport) Addr() stdnet.AddrAddr returns the local bound UDP address.
func (u *UDPTransport) Close() errorClose closes the underlying UDP socket.
func (u *UDPTransport) Err() errorErr returns why the transport stopped receiving: ErrReceiveFailed wrapping the socket's error. Send returns the same error from then on. It is nil while the transport receives, and after Close. Errors about a single datagram, such as an ICMP port unreachable for an earlier send, do not stop it.
func (u *UDPTransport) InboxStats() InboxStatsInboxStats reports what the transport's inbox holds and what its limits dropped or warned about.
func (u *UDPTransport) LocalID() PeerIDLocalID returns this endpoint's PeerID.
func (u *UDPTransport) Peers() []PeerIDPeers returns the sorted list of known remote PeerIDs.
func (u *UDPTransport) Recv() (Packet, bool)Recv pops the next received UDP packet without blocking.
func (u *UDPTransport) RemovePeer(id PeerID)RemovePeer removes a remote peer from the routing table.
func (u *UDPTransport) Send(to PeerID, ch Channel, payload []byte) errorSend transmits payload in a single UDP datagram to the target peer (or all registered peers when to == PeerBroadcast). Keyed peers registered with AddPeerKey receive AEAD-sealed datagrams and return ErrSequenceExhausted once their 32-bit sequence counter would wrap.
UDP has no acknowledgement or retransmission, so ChannelReliableOrdered is refused with ErrUnsupportedChannel instead of quietly losing packets. Use a WebSocket or loopback transport, or a RelayTransport, for lockstep and rollback sessions.
func (u *UDPTransport) SetInboxLimits(l InboxLimits)SetInboxLimits bounds the packets the transport keeps until Recv takes them (see InboxLimits).
type WebSocketServer struct {
// contains filtered or unexported fields
}WebSocketServer accepts RFC 6455 WebSocket clients and exposes them through the standard Transport interface.
Every client runs the connection handshake before its packets reach Recv: Auth.Verify checks its token, the server assigns its ID and tells the client, and NextEvent reports joins, drops, resumes and leaves.
The server pings every client and reports PeerDropped for one that stays silent for Auth.IdleTimeout. Browsers answer pings on their own, so browser clients need no code for it.
Send queues each client's frames in an outbox that a goroutine of the client's own writes out, so a client that reads slowly or not at all never blocks Send or delays the other clients (see OutboxLimits).
func ListenWebSocket(addr string, serverID PeerID, auth Auth) (*WebSocketServer, error)ListenWebSocket starts a pure-Go RFC 6455 WebSocket server on addr. serverID is the server's own PeerID (1 when zero); clients get the IDs after it. auth decides who may connect and how long a dropped client keeps its ID.
func ListenWebSocketTLS(addr string, serverID PeerID, auth Auth, config *tls.Config, allowedOrigins []string) (*WebSocketServer, error)ListenWebSocketTLS starts the server with TLS, so a browser on an HTTPS page can connect with wss:// without a reverse proxy. auth is as for ListenWebSocket. allowedOrigins lists the browser Origins allowed to upgrade; empty allows any, "*" allows all, and an Origin outside the list is refused before the handshake.
func ListenWebSocketTLSFiles(addr string, serverID PeerID, auth Auth, certFile, keyFile string, allowedOrigins []string) (*WebSocketServer, error)ListenWebSocketTLSFiles is ListenWebSocketTLS with a certificate and key loaded from PEM files.
func (s *WebSocketServer) Addr() stdnet.AddrAddr returns the listener's network address.
func (s *WebSocketServer) Close() errorClose stops accepting new clients and closes all active client connections. Each client receives the frames already sent to it and then a close frame, all clients at once; Close waits at most a second for them and cuts off the connections of clients that read too slowly to take theirs by then.
func (s *WebSocketServer) InboxStats() InboxStatsInboxStats reports what the server's inbox holds and what its limits dropped or warned about.
func (s *WebSocketServer) Kick(peer PeerID, reason string) errorKick ends peer's session now: a connected client receives the frames already sent to it, then a close frame with the wsCloseKicked code and the reason, and the session's resume secret is gone, so the client's Reconnect cannot resume it and joins as a new peer only if Auth.Verify accepts its token again. NextEvent reports PeerLeft with the reason. It returns ErrUnknownPeer for an ID with no session (including a handshake still in Verify) and ErrClosed once the server is closed. Kick does not wait for the connection: the client's own goroutine writes the queued frames and the close frame, and whatever a client that reads too slowly has not taken within a second is cut off with the connection.
func (s *WebSocketServer) LocalID() PeerIDLocalID returns the server's PeerID.
func (s *WebSocketServer) NextEvent() (PeerEvent, bool)NextEvent pops the next join, drop, resume or leave without blocking, after ending the sessions whose grace period has passed.
func (s *WebSocketServer) OutboxStats() OutboxStatsOutboxStats reports what the connected clients' outboxes hold and what their limits dropped.
func (s *WebSocketServer) Peers() []PeerIDPeers returns the sorted list of currently connected client PeerIDs. Clients inside their grace period are left out.
func (s *WebSocketServer) Recv() (Packet, bool)Recv pops the next received packet from any connected client without blocking.
func (s *WebSocketServer) Send(to PeerID, ch Channel, payload []byte) errorSend queues payload for a connected client (or all clients when to == PeerBroadcast) and returns without waiting for the connection: each client's own goroutine writes its frames in order (see OutboxLimits). It returns ErrDisconnected for a client inside its grace period or whose session a full outbox has just ended, ErrUnknownPeer for an ID with no session, and ErrPayloadTooLarge for a payload that does not fit a WebSocket message. A write that later fails or times out is not returned by any Send: NextEvent reports it as PeerDropped.
func (s *WebSocketServer) SetInboxLimits(l InboxLimits)SetInboxLimits bounds the packets the server keeps until Recv takes them (see InboxLimits). A client whose queued reliable packets would pass InboxLimits.Reliable has its session ended, as if it had left.
func (s *WebSocketServer) SetOutboxLimits(l OutboxLimits)SetOutboxLimits bounds the frames the server holds for each client before they are written (see OutboxLimits).
type WebSocketTransport struct {
// contains filtered or unexported fields
}WebSocketTransport is a client-side RFC 6455 WebSocket Transport. Binary WebSocket frames carry the 5-byte channel+seq wire header.
The first message each way is the connection handshake: the client presents its token and the server answers with the ID it assigned, or a reason for refusing. A dropped client keeps its session on the server for Auth.GracePeriod, and Reconnect resumes it with the same ID.
func DialWebSocket(rawURL string, token []byte) (*WebSocketTransport, error)DialWebSocket opens an RFC 6455 WebSocket connection to rawURL (ws:// or wss://), presents token in the connection handshake and returns a Transport ready for non-blocking Send/Recv once the server accepts it. The server assigns the client's ID, which LocalID reports. A refusal returns a *RejectError that matches ErrRejected.
The client pings the server every 2 seconds and counts the connection as dropped, reporting ConnDisconnected, when no frame arrives for 10 seconds.
func (wt *WebSocketTransport) Close() errorClose sends a WebSocket close frame and closes the underlying connection. The server reports PeerLeft at once rather than holding the session for a reconnect.
func (wt *WebSocketTransport) Err() errorErr returns why the client is disconnected: a *RejectError, or ErrDisconnected wrapping the I/O error. It is nil while the connection is open.
func (wt *WebSocketTransport) InboxStats() InboxStatsInboxStats reports what the transport's inbox holds and what its limits dropped or warned about.
func (wt *WebSocketTransport) LocalID() PeerIDLocalID returns the PeerID the server assigned this client.
func (wt *WebSocketTransport) Peers() []PeerIDPeers returns the connected server's PeerID, or nil while disconnected or closed.
func (wt *WebSocketTransport) Reconnect() errorReconnect drops the current connection, if any, without a goodbye, dials the server again and resumes the session: within the server's grace period the client keeps its ID, and Resumed reports true. Past it, the server admits the client as a new peer when its token is still valid, and LocalID changes.
func (wt *WebSocketTransport) Recv() (Packet, bool)Recv pops the next received packet without blocking.
func (wt *WebSocketTransport) Resumed() boolResumed reports whether the last handshake resumed an existing session, keeping the client's ID.
func (wt *WebSocketTransport) Send(to PeerID, ch Channel, payload []byte) errorSend frames payload with the 5-byte channel+seq header and sends it as a masked RFC 6455 binary WebSocket frame to the server. It returns ErrDisconnected while the connection is down.
func (wt *WebSocketTransport) SetInboxLimits(l InboxLimits)SetInboxLimits bounds the packets the transport keeps until Recv takes them (see InboxLimits).
func (wt *WebSocketTransport) State() ConnStateState returns the connection state.
type WebTransportOptions struct {
// ServerCertificateHashes pins expected SHA-256 digests (32 bytes each) of the server's leaf X.509 DER certificate.
// In browsers, these are passed as serverCertificateHashes to the WebTransport constructor so self-signed development certificates (at most 14 days validity per the WebTransport specification) work without installing a root CA.
// On native targets, when non-empty, certificate verification accepts a server whose leaf certificate SHA-256 digest matches any entry instead of verifying against system roots.
ServerCertificateHashes [][]byte
}WebTransportOptions configures DialWebTransport.
type WebTransportServer struct {
// contains filtered or unexported fields
}WebTransportServer accepts WebTransport clients over HTTP/3 and QUIC and exposes them through the standard Transport and RelayServer interfaces.
ChannelReliableOrdered packets travel over each client's bidirectional QUIC stream, and ChannelUnreliable packets travel as independent QUIC datagrams. Every client runs the connection handshake on the bidirectional stream before its packets reach Recv: Auth.Verify checks its token, the server assigns its ID and tells the client, and NextEvent reports joins, drops, resumes and leaves.
Send queues each client's reliable frames in an outbox that a goroutine of the client's own writes to its stream, and its unreliable datagrams in a second outbox that another goroutine hands to QUIC, so a client that stops reading the stream, or whose acknowledgements stop coming, never blocks Send or delays the other clients (see OutboxLimits).
func ListenWebTransport(addr string, serverID PeerID, auth Auth, cfg *tls.Config, allowedOrigins []string) (*WebTransportServer, error)ListenWebTransport starts a WebTransport server over QUIC/HTTP/3 on addr. serverID is the server's own PeerID (1 when zero); clients get the IDs after it. auth decides who may connect and how long a dropped client keeps its ID. cfg provides the TLS 1.3 certificate and is required. allowedOrigins lists the browser Origins allowed to connect; empty allows any, "*" allows all, and an Origin outside the list is refused with 403 before the handshake.
func ListenWebTransportFiles(addr string, serverID PeerID, auth Auth, certFile, keyFile string, allowedOrigins []string) (*WebTransportServer, error)ListenWebTransportFiles is ListenWebTransport with a certificate and key loaded from PEM files.
func (s *WebTransportServer) Addr() stdnet.AddrAddr returns the listener's UDP network address.
func (s *WebTransportServer) Close() errorClose stops accepting new clients and closes all active client sessions and the underlying UDP socket.
func (s *WebTransportServer) InboxStats() InboxStatsInboxStats reports what the server's inbox holds and what its limits dropped or warned about.
func (s *WebTransportServer) LocalID() PeerIDLocalID returns the server's PeerID.
func (s *WebTransportServer) NextEvent() (PeerEvent, bool)NextEvent pops the next join, drop, resume or leave without blocking, after ending the sessions whose grace period has passed.
func (s *WebTransportServer) OutboxStats() OutboxStatsOutboxStats reports what the connected clients' outboxes hold and what their limits dropped.
func (s *WebTransportServer) Peers() []PeerIDPeers returns the sorted list of currently connected client PeerIDs. Clients inside their grace period are left out.
func (s *WebTransportServer) Recv() (Packet, bool)Recv pops the next received packet from any connected client without blocking.
func (s *WebTransportServer) Send(to PeerID, ch Channel, payload []byte) errorSend queues payload for a connected client (or all clients when to == PeerBroadcast) and returns without waiting for the connection: each client's own goroutines write its frames in order (see OutboxLimits). ChannelReliableOrdered frames travel on each client's bidirectional stream; ChannelUnreliable frames travel as independent QUIC datagrams (returning ErrPayloadTooLarge if payload exceeds the QUIC datagram MTU). It returns ErrDisconnected for a client inside its grace period or whose session a full outbox has just ended, and ErrUnknownPeer for an ID with no session. A write that later fails or times out is not returned by any Send: NextEvent reports it as PeerDropped.
func (s *WebTransportServer) SetInboxLimits(l InboxLimits)SetInboxLimits bounds the packets the server keeps until Recv takes them (see InboxLimits). A client whose queued reliable packets would pass InboxLimits.Reliable has its session ended, as if it had left.
func (s *WebTransportServer) SetOutboxLimits(l OutboxLimits)SetOutboxLimits bounds the frames the server holds for each client before they are written (see OutboxLimits). Each client's reliable frames and its unreliable datagrams have an outbox of their own, each with these limits.
type WebTransportTransport struct {
// contains filtered or unexported fields
}WebTransportTransport is a client-side WebTransport Transport over HTTP/3 and QUIC.
ChannelReliableOrdered packets travel over one bidirectional QUIC stream with 4-byte length-prefixed frames; ChannelUnreliable packets travel as independent QUIC datagrams so a lost packet never blocks newer unreliable updates.
The first message each way on the bidirectional stream is the connection handshake: the client presents its token and the server answers with the ID it assigned, or a reason for refusing. A dropped client keeps its session on the server for Auth.GracePeriod, and Reconnect resumes it with the same ID.
func DialWebTransport(rawURL string, token []byte, opts WebTransportOptions) (*WebTransportTransport, error)DialWebTransport opens a WebTransport session to rawURL (https://), presents token in the connection handshake on the reliable stream, and returns a Transport ready for non-blocking Send/Recv once the server accepts it. The server assigns the client's ID, which LocalID reports. A refusal returns a *RejectError that matches ErrRejected.
When opts.ServerCertificateHashes is non-empty, certificate verification matches the server's leaf certificate SHA-256 digest against the provided hashes instead of system root CAs.
func (wt *WebTransportTransport) Close() errorClose sends a clean goodbye on the reliable stream and closes the WebTransport session so the server reports PeerLeft at once rather than holding the session for a reconnect.
func (wt *WebTransportTransport) Err() errorErr returns why the client is disconnected: a *RejectError, or ErrDisconnected wrapping the I/O error. It is nil while the connection is open.
func (wt *WebTransportTransport) InboxStats() InboxStatsInboxStats reports what the transport's inbox holds and what its limits dropped or warned about.
func (wt *WebTransportTransport) LocalID() PeerIDLocalID returns the PeerID the server assigned this client.
func (wt *WebTransportTransport) Peers() []PeerIDPeers returns the connected server's PeerID, or nil while disconnected or closed.
func (wt *WebTransportTransport) Reconnect() errorReconnect drops the current WebTransport session without a goodbye (sending wtCloseReconnect so the server keeps the session for Auth.GracePeriod), dials the server again, and resumes the session: within the server's grace period the client keeps its ID, and Resumed reports true. Past it, the server admits the client as a new peer when its token is still valid, and LocalID changes.
func (wt *WebTransportTransport) Recv() (Packet, bool)Recv pops the next received packet without blocking.
func (wt *WebTransportTransport) Resumed() boolResumed reports whether the last handshake resumed an existing session, keeping the client's ID.
func (wt *WebTransportTransport) Send(to PeerID, ch Channel, payload []byte) errorSend transmits payload to the server. ChannelReliableOrdered frames travel on the bidirectional QUIC stream; ChannelUnreliable frames travel as independent QUIC datagrams (returning ErrPayloadTooLarge if payload exceeds the QUIC datagram MTU).
func (wt *WebTransportTransport) SetInboxLimits(l InboxLimits)SetInboxLimits bounds the packets the transport keeps until Recv takes them (see InboxLimits).
func (wt *WebTransportTransport) State() ConnStateState returns the connection state.