Documentation
¶
Overview ¶
Package lan is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package lan advertises and discovers multiplayer games on the local network over DNS-SD (wrapping NSGo's core.Scope.AdvertiseService and core.Scope.BrowseServices) with a validated game record and deterministic RFC 6763 TXT metadata.
Index ¶
- Constants
- Variables
- func Browse(cx *core.Scope, serviceType string, onEvent func(Event)) (stop func(), err error)
- func DecodeTXT(data []byte) (map[string]string, error)
- type Advertisement
- type Event
- type Game
- func (g Game) Addr() string
- func (g Game) Clone() Game
- func (g Game) EffectiveTransport() Transport
- func (g Game) EncodeTXT() ([]byte, error)
- func (g Game) Equal(other Game) bool
- func (g Game) LocalService() (core.LocalService, error)
- func (g Game) TXT() map[string]string
- func (g Game) Validate() error
- func (g Game) WebSocketURL(path string) string
- type Transport
Examples ¶
Constants ¶
const ( // MaxNameBytes is the maximum UTF-8 byte length of a DNS-SD instance name (RFC 6763). MaxNameBytes = 63 // MaxTXTEntryBytes is the maximum byte length of a single "key=value" TXT string (RFC 6763 §6.1). MaxTXTEntryBytes = 255 // MaxTXTBytes is the maximum total wire size of a LAN game's DNS-SD TXT record so it fits in a single mDNS packet without fragmentation (RFC 6763 §6.2). MaxTXTBytes = 1300 // MaxInfoKeys is the maximum number of custom Info TXT attributes carried by a Game advertisement or decoded from an untrusted remote record. MaxInfoKeys = 32 )
Variables ¶
var ( ErrDiscoveryUnavailable = core.ErrDiscoveryUnavailable // ErrAdvertisementStopped reports an Update or SetPlayers call on an Advertisement that has already been stopped. ErrAdvertisementStopped = errors.New("lan: advertisement stopped") )
Functions ¶
func Browse ¶
Browse watches the local network for games advertised under serviceType (such as "_mygame._udp" or "_mygame._tcp") and delivers parsed Event values on the engine goroutine. Call stop on the engine goroutine to end browsing; disposing cx also stops it. On web targets (js/wasm) or platforms without DNS-SD support it returns ErrDiscoveryUnavailable.
Types ¶
type Advertisement ¶
type Advertisement struct {
// contains filtered or unexported fields
}
Advertisement is a live DNS-SD advertisement for a LAN game.
Call Update, SetPlayers, or SetLobby on the engine goroutine whenever player count or lobby state changes to republish the TXT record. Call Stop on the engine goroutine to withdraw the advertisement; disposing the owning core.Scope also stops it automatically.
func Advertise ¶
func Advertise(cx *core.Scope, game Game) (*Advertisement, error)
Advertise validates game and publishes it on the local network using DNS-SD while cx is alive. On web targets (js/wasm) or platforms without DNS-SD support it returns ErrDiscoveryUnavailable.
func AdvertiseWith ¶
AdvertiseWith is Advertise with an asynchronous platform error callback invoked on the engine goroutine if publishing later fails.
func (*Advertisement) Game ¶
func (a *Advertisement) Game() Game
Game returns a deep copy of the currently advertised game record.
func (*Advertisement) SetLobby ¶
func (a *Advertisement) SetLobby(state string, players, capacity int, password bool, info map[string]string) error
SetLobby updates lobby state fields (state, player counts, password flag, and extra Info settings) and refreshes the TXT record.
func (*Advertisement) SetPlayers ¶
func (a *Advertisement) SetPlayers(players int) error
SetPlayers updates the advertised player count and refreshes the TXT record.
func (*Advertisement) Stop ¶
func (a *Advertisement) Stop()
Stop withdraws the DNS-SD advertisement. It is safe to call more than once.
func (*Advertisement) Update ¶
func (a *Advertisement) Update(game Game) error
Update validates game and refreshes the DNS-SD advertisement when any published field (name, type, port, or TXT attributes) has changed. If game fails validation, the existing advertisement remains active unchanged. Calling Update after Stop returns ErrAdvertisementStopped.
type Event ¶
Event reports a discovered LAN game, its removal from the network, or a browse failure.
type Game ¶
type Game struct {
// Name is the display name and DNS-SD instance label (1..63 valid UTF-8 bytes, no NUL).
Name string
// Type is the DNS-SD service type, such as "_mygame._udp" or "_mygame._tcp".
Type string
// Address is the resolved DNS hostname or IP address of a discovered game; ignored when advertising.
Address string
// Version is the game or protocol build string advertised in the TXT "version" attribute.
Version string
// Port is the listening port (1..65535).
Port int
// Transport names the netplay transport on Port ("udp", "ws", "wss", or "webtransport").
// When empty, EffectiveTransport infers TransportUDP for "_udp" types and TransportWebSocket for "_tcp" types.
Transport Transport
// Players is the current player count in the game or lobby.
Players int
// Capacity is the maximum player count; zero means no fixed cap.
Capacity int
// Password reports whether joining requires a password.
Password bool
// State is the optional lobby or match state (such as "waiting", "running", or "ended"), matching gameserver.RoomState.String().
State string
// Info holds optional application or lobby TXT attributes (such as "mode" or "map").
// Keys must be valid RFC 6763 printable ASCII without '=', unique case-insensitively,
// and must not collide with reserved keys ("name", "version", "players", "password", "transport", "state").
Info map[string]string
}
Game describes a multiplayer game advertised or discovered on the local network.
func FromService ¶
func FromService(service core.LocalService) Game
FromService converts a discovered NSGo core.LocalService into a Game record, safely handling missing or malformed TXT fields.
func ParseTXT ¶
ParseTXT decodes an untrusted TXT attribute map into a Game's metadata fields. Malformed values are safely ignored or clamped to zero values, keys are normalized to lowercase in deterministic order, and custom Info entries are bounded by MaxInfoKeys and MaxTXTEntryBytes.
func (Game) Addr ¶
Addr returns the host:port address suitable for netplay.DialUDP or TCP dialing, bracketing IPv6 addresses automatically. It returns "" if Address is empty or invalid, or Port is out of range.
Example ¶
Addr and WebSocketURL format discovered endpoints for netplay.DialUDP and netplay.DialWebSocket.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/online/lan"
)
func main() {
udp := lan.Game{Address: "192.168.1.42", Port: 7777, Type: "_game._udp"}
ws := lan.Game{Address: "host.local.", Port: 8080, Type: "_game._tcp", Transport: lan.TransportWebSocket}
fmt.Println(udp.Addr())
fmt.Println(ws.WebSocketURL("/play"))
}
Output: 192.168.1.42:7777 ws://host.local.:8080/play
func (Game) EffectiveTransport ¶
EffectiveTransport returns g.Transport when set, or infers TransportUDP for "_udp" service types and TransportWebSocket for "_tcp" service types.
func (Game) EncodeTXT ¶
EncodeTXT validates g and encodes its TXT attributes into deterministic RFC 6763 length-prefixed wire bytes sorted by lowercase key.
func (Game) LocalService ¶
func (g Game) LocalService() (core.LocalService, error)
LocalService validates g and converts it into a core.LocalService ready for NSGo's Scope.AdvertiseService.
func (Game) TXT ¶
TXT returns the deterministic DNS-SD TXT attribute map for g. Reserved keys ("name", "version", "players", "password", "transport", and optional "state") are always populated from g's structured fields; custom Info keys are normalized to lowercase and included alongside them.
Example ¶
A host validates its advertisement and publishes TXT as the discovery record's metadata; the map is printed in sorted key order.
package main
import (
"fmt"
"maps"
"slices"
"github.com/nsgo-dev/game/pkg/online/lan"
)
func main() {
g := lan.Game{Name: "Cave Run", Type: "_game._udp", Version: "1.2.0", Port: 7777, Players: 1, Capacity: 4}
if err := g.Validate(); err != nil {
fmt.Println(err)
return
}
txt := g.TXT()
for _, k := range slices.Sorted(maps.Keys(txt)) {
fmt.Printf("%s=%s\n", k, txt[k])
}
}
Output: name=Cave Run password=false players=1/4 transport=udp version=1.2.0
func (Game) Validate ¶
Validate checks a game advertisement against DNS-SD service type, name, port, player count, transport, and RFC 6763 TXT record constraints.
Example ¶
Validate refuses an advertisement without a name or with more players than it has room for.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/online/lan"
)
func main() {
fmt.Println(lan.Game{Type: "_game._udp", Port: 7777}.Validate())
fmt.Println(lan.Game{Name: "Cave Run", Type: "_game._udp", Port: 7777, Players: 5, Capacity: 4}.Validate())
}
Output: lan: invalid game advertisement lan: invalid player counts
func (Game) WebSocketURL ¶
WebSocketURL formats a ws:// or wss:// URL for a WebSocket-backed LAN game, appending path (leading '/' added when needed). IPv6 zone identifiers are percent-encoded per RFC 6874. It returns "" when Addr() is empty, path contains control characters or invalid UTF-8, or EffectiveTransport is neither TransportWebSocket nor TransportWebSocketTLS.
type Transport ¶
type Transport string
Transport identifies the netplay transport a LAN game accepts on its listening port.
const ( // TransportUDP advertises a netplay UDPServer (the default for _udp service types). TransportUDP Transport = "udp" // TransportWebSocket advertises a plaintext netplay WebSocketServer (ws://). TransportWebSocket Transport = "ws" // TransportWebSocketTLS advertises a TLS netplay WebSocketServer (wss://). TransportWebSocketTLS Transport = "wss" // TransportWebTransport advertises an HTTP/3 QUIC netplay WebTransportServer (https://). TransportWebTransport Transport = "webtransport" )