GitHubLoslegen

Die API-Referenz stammt aus den Go-Doc-Kommentaren im Quellcode und ist auf Englisch verfasst.

package net

import "github.com/nsgo-dev/game/pkg/net"

Übersicht

Package net provides cross-target multiplayer primitives for NSGo games:

  • Transport abstraction with deterministic in-memory loopback, pure-Go RFC 6455 WebSocket (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 or UDP for players who cannot reach each other directly.

Index

Konstanten

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 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 (
	// 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 << 16

MaxEntitiesPerSnapshot 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 << 20

MaxJoinStateSize 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 = 4096

MaxTokenSize is the largest credential a client may present in the handshake.

const ReplicationVersion = 2

ReplicationVersion 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")
)
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 = errors.New("net: invalid packet")
	// ErrPayloadTooLarge is returned when a payload exceeds transport limits.
	ErrPayloadTooLarge = errors.New("net: payload too large")
	// 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 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.

Funktionen

func ChecksumBytes(data []byte) uint64

ChecksumBytes computes a deterministic 64-bit FNV-1a checksum over data.

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.
	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
}

Auth configures the connection handshake that ListenWebSocket 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 Channel uint8

Channel 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() string

String 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) *ClientWorld

NewClientWorld 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() error

Err 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) []EntityState

Interpolate 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() float32

LastReconcileError 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) int

PendingPredictions returns the number of unacknowledged predicted inputs buffered for id.

func (c *ClientWorld) Poll() int

Poll 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() int

Reconciliations 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() ComponentState

Clone returns a deep copy of ComponentState (duplicating Props).

type ConnState uint8

ConnState 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
)
func (s ConnState) String() string

String returns the state's name.

type DesyncEvent struct {
	Tick           uint32
	LocalPeer      PeerID
	RemotePeer     PeerID
	LocalChecksum  uint64
	RemoteChecksum uint64
}

DesyncEvent describes a detected state checksum divergence between peers.

type EntityID uint32

EntityID 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() EntityState

Clone 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, 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 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) *LockstepSession

NewLockstepSession creates a strict lockstep session.

func (s *LockstepSession) Active() bool

Active 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() []DesyncEvent

Desyncs returns a copy of all DesyncEvents observed so far.

func (s *LockstepSession) Members() []PeerID

Members 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() bool

Step 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) error

SubmitInput 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() uint32

Tick 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) *LoopbackHub

NewLoopbackHub creates a new deterministic in-memory network hub.

func (h *LoopbackHub) AddPeer(id PeerID) *LoopbackTransport

AddPeer 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() LoopbackConfig

Config returns the current network simulation configuration.

func (h *LoopbackHub) InFlight() int

InFlight returns the number of packets currently in transit.

func (h *LoopbackHub) Now() time.Duration

Now 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() error

Close disconnects this endpoint from its LoopbackHub.

func (t *LoopbackTransport) InboxStats() InboxStats

InboxStats reports what the transport's inbox holds and what its limits dropped or warned about.

func (t *LoopbackTransport) LocalID() PeerID

LocalID returns this endpoint's PeerID.

func (t *LoopbackTransport) Peers() []PeerID

Peers 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) error

Send 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 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
}

PeerEvent is one change to a peer's session, reported by a server's NextEvent.

type PeerEventKind uint8

PeerEventKind 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() string

String 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 uint32

PeerID uniquely identifies a participant in a multiplayer session.

const PeerBroadcast PeerID = 0

PeerBroadcast 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() string

Error returns the rejection with its reason.

func (e *RejectError) Is(target error) bool

Is reports whether target is ErrRejected.

type Relay

Nur auf linux, macos, windows, android, iosQuellcode
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

Nur auf linux, macos, windows, android, iosQuellcode
func NewRelay(cfg RelayConfig) (*Relay, error)

NewRelay returns a relay for cfg. It fails when cfg.Join is nil.

func (*Relay) Auth

Nur auf linux, macos, windows, android, iosQuellcode
func (r *Relay) Auth(base Auth) Auth

Auth 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 (*Relay) Serve

Nur auf linux, macos, windows, android, iosQuellcode
func (r *Relay) Serve(ctx context.Context, srv RelayServer) error

Serve 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 (*Relay) Stats

Nur auf linux, macos, windows, android, iosQuellcode
func (r *Relay) Stats() RelayStats

Stats returns the relay's current counts.

type RelayConfig

Nur auf linux, macos, windows, android, iosQuellcode
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

Nur auf linux, macos, windows, android, iosQuellcode
type RelayServer interface {
	Transport
	PeerEvents
}

RelayServer is a server transport a Relay serves: WebSocketServer or UDPServer.

type RelayStats

Nur auf linux, macos, windows, android, iosQuellcode
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) 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) *RelayTransport

NewRelayTransport 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() error

Close closes the inner transport.

func (rt *RelayTransport) InboxStats() InboxStats

InboxStats reports what the transport's inbox holds and what its limits dropped or warned about.

func (rt *RelayTransport) LocalID() PeerID

LocalID returns the ID the relay assigned this client.

func (rt *RelayTransport) Peers() []PeerID

Peers 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) error

Send 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) *RollbackSession

NewRollbackSession creates a GGPO-style rollback session.

func (s *RollbackSession) Active() bool

Active 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() int64

ConfirmedTick returns the highest tick for which all peers' inputs are confirmed, or -1 if no tick is fully confirmed yet.

func (s *RollbackSession) Desyncs() []DesyncEvent

Desyncs returns a copy of all detected DesyncEvents.

func (s *RollbackSession) Members() []PeerID

Members 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() error

Poll 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() RollbackStats

Stats returns a snapshot of the rollback session's metrics.

func (s *RollbackSession) Step(localInput InputFrame) error

Step 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. It returns ErrSessionBacklog, after simulating the tick, when a remote peer has become unreachable for too long (see Poll).

func (s *RollbackSession) Tick() uint32

Tick returns the current simulation tick (number of ticks executed so far). A joining peer's count starts at its join tick.

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) *ServerWorld

NewServerWorld 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) bool

Despawn removes an entity from the authoritative world. Returns false if id does not exist.

func (w *ServerWorld) Entities() []EntityState

Entities 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() uint32

Epoch returns the replication epoch every snapshot of this world carries.

func (w *ServerWorld) PeerErr(peer PeerID) error

PeerErr 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) EntityID

Spawn creates a new entity with the given initial state and returns its assigned EntityID.

func (w *ServerWorld) Stats() ReplicationStats

Stats returns cumulative replication bandwidth and snapshot statistics.

func (w *ServerWorld) Step(tick uint32) error

Step 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) bool

Update 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).

type UDPClient

Nur auf linux, macos, windows, android, iosQuellcode
type UDPClient struct {
	// contains filtered or unexported fields
}

UDPClient is a native UDP Transport connected to a UDPServer. DialUDP runs the connection handshake, after which every datagram is sealed with the session's key. The client pings the server while idle and reports itself disconnected when the server stays silent for 10 seconds; Reconnect resumes the session with the same ID within the server's grace period.

func DialUDP

Nur auf linux, macos, windows, android, iosQuellcode
func DialUDP(addr string, token []byte) (*UDPClient, error)

DialUDP connects to the UDPServer at addr, presents token in the connection handshake and returns once the server accepts it. The server assigns the client's ID, which LocalID reports. A refusal returns a *RejectError that matches ErrRejected.

func (*UDPClient) Close

Nur auf linux, macos, windows, android, iosQuellcode
func (c *UDPClient) Close() error

Close sends the server a goodbye, so it reports PeerLeft at once rather than holding the session for a reconnect, and closes the socket.

func (*UDPClient) Err

Nur auf linux, macos, windows, android, iosQuellcode
func (c *UDPClient) Err() error

Err 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 (*UDPClient) InboxStats

Nur auf linux, macos, windows, android, iosQuellcode
func (c *UDPClient) InboxStats() InboxStats

InboxStats reports what the client's inbox holds and what its limits dropped or warned about.

func (*UDPClient) LocalID

Nur auf linux, macos, windows, android, iosQuellcode
func (c *UDPClient) LocalID() PeerID

LocalID returns the PeerID the server assigned this client.

func (*UDPClient) Peers

Nur auf linux, macos, windows, android, iosQuellcode
func (c *UDPClient) Peers() []PeerID

Peers returns the server's PeerID, or nil while disconnected or closed.

func (*UDPClient) Reconnect

Nur auf linux, macos, windows, android, iosQuellcode
func (c *UDPClient) Reconnect() error

Reconnect drops the current socket without a goodbye, opens a new one 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 (*UDPClient) Recv

Nur auf linux, macos, windows, android, iosQuellcode
func (c *UDPClient) Recv() (Packet, bool)

Recv pops the next authenticated packet from the server without blocking.

func (*UDPClient) Resumed

Nur auf linux, macos, windows, android, iosQuellcode
func (c *UDPClient) Resumed() bool

Resumed reports whether the last handshake resumed an existing session, keeping the client's ID.

func (*UDPClient) Send

Nur auf linux, macos, windows, android, iosQuellcode
func (c *UDPClient) Send(to PeerID, ch Channel, payload []byte) error

Send seals payload with the session key and sends it to the server in one datagram. It refuses ChannelReliableOrdered with ErrUnsupportedChannel and returns ErrDisconnected while the connection is down.

func (*UDPClient) SetInboxLimits

Nur auf linux, macos, windows, android, iosQuellcode
func (c *UDPClient) SetInboxLimits(l InboxLimits)

SetInboxLimits bounds the packets the client keeps until Recv takes them (see InboxLimits).

func (*UDPClient) State

Nur auf linux, macos, windows, android, iosQuellcode
func (c *UDPClient) State() ConnState

State returns the connection state.

type UDPServer

Nur auf linux, macos, windows, android, iosQuellcode
type UDPServer struct {
	// contains filtered or unexported fields
}

UDPServer is a native UDP Transport for a server whose clients connect with DialUDP. Each client runs the connection handshake before its packets reach Recv: Auth.Verify checks its token and the server assigns its ID. After that the client is bound to the address it shook hands from and to a per-session key, so a datagram from another address, or without the key, is dropped instead of reaching Recv or moving the peer.

UDP has no connection, so a client that stays silent for Auth.IdleTimeout counts as dropped; DialUDP clients ping every second while idle. Datagrams are authenticated, not encrypted.

The binding stops attackers who cannot see the traffic. The handshake itself travels in the clear: the hello carries the token, and the welcome carries the session key and resume secret. Anyone who can observe it, on shared Wi-Fi or any hop on the path, can forge datagrams for the session and resume it from their own address, taking it over. Issue UDP tokens that are short-lived and single-use, and use WebSocket over wss:// where an on-path observer is a concern.

func ListenUDPServer

Nur auf linux, macos, windows, android, iosQuellcode
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.

func (*UDPServer) Addr

Nur auf linux, macos, windows, android, iosQuellcode
func (s *UDPServer) Addr() stdnet.Addr

Addr returns the local bound UDP address.

func (*UDPServer) Close

Nur auf linux, macos, windows, android, iosQuellcode
func (s *UDPServer) Close() error

Close closes the UDP socket.

func (*UDPServer) Err

Nur auf linux, macos, windows, android, iosQuellcode
func (s *UDPServer) Err() error

Err 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 (*UDPServer) InboxStats

Nur auf linux, macos, windows, android, iosQuellcode
func (s *UDPServer) InboxStats() InboxStats

InboxStats reports what the server's inbox holds and what its limits dropped or warned about.

func (*UDPServer) LocalID

Nur auf linux, macos, windows, android, iosQuellcode
func (s *UDPServer) LocalID() PeerID

LocalID returns the server's PeerID.

func (*UDPServer) NextEvent

Nur auf linux, macos, windows, android, iosQuellcode
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 (*UDPServer) Peers

Nur auf linux, macos, windows, android, iosQuellcode
func (s *UDPServer) Peers() []PeerID

Peers returns the sorted IDs of connected clients. Clients inside their grace period are left out.

func (*UDPServer) Recv

Nur auf linux, macos, windows, android, iosQuellcode
func (s *UDPServer) Recv() (Packet, bool)

Recv pops the next authenticated packet without blocking.

func (*UDPServer) Send

Nur auf linux, macos, windows, android, iosQuellcode
func (s *UDPServer) Send(to PeerID, ch Channel, payload []byte) error

Send seals payload with the client's session 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 and ErrUnknownPeer for an ID with no session.

func (*UDPServer) SetInboxLimits

Nur auf linux, macos, windows, android, iosQuellcode
func (s *UDPServer) SetInboxLimits(l InboxLimits)

SetInboxLimits bounds the packets the server keeps until Recv takes them (see InboxLimits).

type UDPTransport

Nur auf linux, macos, windows, android, iosQuellcode
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. Each datagram carries a 9-byte header (from PeerID + channel + sequence number) so peers can exchange packets directly without a TCP handshake.

Both sides register each other with AddPeer, and a datagram is accepted only from the address registered for the PeerID it claims, so a spoofed From header can neither add a peer nor move one. A server whose clients are not known in advance uses ListenUDPServer and DialUDP, which authenticate each client and bind it to its address.

func ListenUDP

Nur auf linux, macos, windows, android, iosQuellcode
func ListenUDP(addr string, localID PeerID) (*UDPTransport, error)

ListenUDP binds a UDP socket on addr for localID and starts receiving datagrams.

func (*UDPTransport) AddPeer

Nur auf linux, macos, windows, android, iosQuellcode
func (u *UDPTransport) AddPeer(id PeerID, addr string) error

AddPeer registers or updates a remote peer's UDP address. Datagrams claiming to be from id are accepted only from this address.

func (*UDPTransport) Addr

Nur auf linux, macos, windows, android, iosQuellcode
func (u *UDPTransport) Addr() stdnet.Addr

Addr returns the local bound UDP address.

func (*UDPTransport) Close

Nur auf linux, macos, windows, android, iosQuellcode
func (u *UDPTransport) Close() error

Close closes the underlying UDP socket.

func (*UDPTransport) Err

Nur auf linux, macos, windows, android, iosQuellcode
func (u *UDPTransport) Err() error

Err 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 (*UDPTransport) InboxStats

Nur auf linux, macos, windows, android, iosQuellcode
func (u *UDPTransport) InboxStats() InboxStats

InboxStats reports what the transport's inbox holds and what its limits dropped or warned about.

func (*UDPTransport) LocalID

Nur auf linux, macos, windows, android, iosQuellcode
func (u *UDPTransport) LocalID() PeerID

LocalID returns this endpoint's PeerID.

func (*UDPTransport) Peers

Nur auf linux, macos, windows, android, iosQuellcode
func (u *UDPTransport) Peers() []PeerID

Peers returns the sorted list of known remote PeerIDs.

func (*UDPTransport) Recv

Nur auf linux, macos, windows, android, iosQuellcode
func (u *UDPTransport) Recv() (Packet, bool)

Recv pops the next received UDP packet without blocking.

func (*UDPTransport) RemovePeer

Nur auf linux, macos, windows, android, iosQuellcode
func (u *UDPTransport) RemovePeer(id PeerID)

RemovePeer removes a remote peer from the routing table.

func (*UDPTransport) Send

Nur auf linux, macos, windows, android, iosQuellcode
func (u *UDPTransport) Send(to PeerID, ch Channel, payload []byte) error

Send transmits payload in a single UDP datagram to the target peer (or all registered peers when to == PeerBroadcast).

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 (*UDPTransport) SetInboxLimits

Nur auf linux, macos, windows, android, iosQuellcode
func (u *UDPTransport) SetInboxLimits(l InboxLimits)

SetInboxLimits bounds the packets the transport keeps until Recv takes them (see InboxLimits).

type WebSocketServer

Nur auf linux, macos, windows, android, iosQuellcode
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.

func ListenWebSocket

Nur auf linux, macos, windows, android, iosQuellcode
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

Nur auf linux, macos, windows, android, iosQuellcode
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

Nur auf linux, macos, windows, android, iosQuellcode
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 (*WebSocketServer) Addr

Nur auf linux, macos, windows, android, iosQuellcode
func (s *WebSocketServer) Addr() stdnet.Addr

Addr returns the listener's network address.

func (*WebSocketServer) Close

Nur auf linux, macos, windows, android, iosQuellcode
func (s *WebSocketServer) Close() error

Close stops accepting new clients and closes all active client connections. It sends each client a close frame, waiting at most a second for clients that do not read, all at once rather than one after another.

func (*WebSocketServer) InboxStats

Nur auf linux, macos, windows, android, iosQuellcode
func (s *WebSocketServer) InboxStats() InboxStats

InboxStats reports what the server's inbox holds and what its limits dropped or warned about.

func (*WebSocketServer) LocalID

Nur auf linux, macos, windows, android, iosQuellcode
func (s *WebSocketServer) LocalID() PeerID

LocalID returns the server's PeerID.

func (*WebSocketServer) NextEvent

Nur auf linux, macos, windows, android, iosQuellcode
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 (*WebSocketServer) Peers

Nur auf linux, macos, windows, android, iosQuellcode
func (s *WebSocketServer) Peers() []PeerID

Peers returns the sorted list of currently connected client PeerIDs. Clients inside their grace period are left out.

func (*WebSocketServer) Recv

Nur auf linux, macos, windows, android, iosQuellcode
func (s *WebSocketServer) Recv() (Packet, bool)

Recv pops the next received packet from any connected client without blocking.

func (*WebSocketServer) Send

Nur auf linux, macos, windows, android, iosQuellcode
func (s *WebSocketServer) Send(to PeerID, ch Channel, payload []byte) error

Send transmits payload to a connected client (or all clients when to == PeerBroadcast). It returns ErrDisconnected for a client inside its grace period and ErrUnknownPeer for an ID with no session.

func (*WebSocketServer) SetInboxLimits

Nur auf linux, macos, windows, android, iosQuellcode
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.

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() error

Close 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() error

Err 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() InboxStats

InboxStats reports what the transport's inbox holds and what its limits dropped or warned about.

func (wt *WebSocketTransport) LocalID() PeerID

LocalID returns the PeerID the server assigned this client.

func (wt *WebSocketTransport) Peers() []PeerID

Peers returns the connected server's PeerID, or nil while disconnected or closed.

func (wt *WebSocketTransport) Reconnect() error

Reconnect 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() bool

Resumed reports whether the last handshake resumed an existing session, keeping the client's ID.

func (wt *WebSocketTransport) Send(to PeerID, ch Channel, payload []byte) error

Send 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() ConnState

State returns the connection state.