Playing together over a network

Sloppy has three ways for players on different machines to play one game. Which one fits depends on the game:

Messages (import net)Rollback (netplay.session)Client and server (netplay.server, netplay.client)
What travelswhatever the game sendseach player's input, every tickinputs to the server, the world back
Who runs the gamethe game decides (often one host)every machine runs all of itthe server
Feelsas fast as the networklocal: others' moves shown at once, corrected a few frames later at worstone's own moves at once; others a little in the past
Playersany2 to 4many
Good forturn-based games, chat, lobbies, simple gamesfighting, sports, action games for a fewshooters, many players, keeping cheating out
Exampleexamples/netpongexamples/duelexamples/arena
Web pagesconnect to a native server, or straight to another game with invite codesinvite codes, or through a relay, then straight to each other (WebRTC)connect to a native server

Messages

import net sends messages (text or bytes) over WebSockets: net.listen(port) in a native program, net.connect(host, port) from a native program or a web page, net.receive() each frame for what happened. Messages arrive whole and in order. Native programs can also send UDP datagrams (net.udp), which may be lost or come out of order but never wait for each other. See the library.

With no server at all: invite codes. net.invite() makes a peer and net.invite_code(p) a code (120 to 250 characters: a box to paste one into needs max_chars of 400) for the player to send their friend any way they like: a chat message. The friend's game joins with it, net.join_invite(code), and its net.invite_code(p) is a reply code to send back, which the first game takes with net.accept_reply(p, reply). The two games then connect straight to each other (WebRTC: the browser's own in a web page, Sloppy's in a native program), web pages and native programs alike, on one Wi-Fi or across the internet; after that the peer is as any other. Nothing runs anywhere but the two games: a public STUN server (Google's, rtc.rtc_stun_servers) only tells each game how it looks from the internet. Most home networks connect so; some (mobile data, many schools' and offices') let no outside connection in, and need a relay: a TURN server, which passes the two games' packets on. net.turn_server("turn:host:3478", user, password), before inviting, offers a path through one (your own, coturn, or a service's: some have a free tier; its password goes into every copy of the game), used only when no straight path works. net.invite(reliable = false) sends messages that may be lost or come in another order but never wait: a fast game's state. net.code_kind(code) says what a pasted code is ("invite", "reply", or "" for neither: cut short, or something else). A game that ends (quit, its window closed, a page closed) tells its peers so at once; one that vanishes (switched off, its network gone) is .left after 15 s of silence. A message may be up to 16 MB. One native game can be the host of many: 128 peers joined one host by invite codes in about 2 seconds and stayed (a load test), so a big game hosted by a player needs no server of its own. import invite has the screens for all this (below).

A screen of one's own, whole (the inviter's side and the friend's in one program):

import net

p = -1                                  # the friend, once there is an invite or a join
mine = ""                               # this side's code, to send
pasted = ""                             # theirs, pasted in
connected = false

update = (dt: f64):
    global connected, mine
    if p >= 0 and len(mine) == 0: mine = net.invite_code(p)     # ("" for a moment)
    loop e in net.receive():
        if e.kind == .joined: connected = true
        else if e.kind == .left: print("no: {net.why(e.peer)}")
        else if e.kind == .message: print("they said {e.text}")

draw = ():
    global p, pasted
    clear()
    if connected:
        if hud_button(Rect(40, 40, 200, 44), "Say hello"): net.send(p, "hello")
        return
    if p < 0:
        if hud_button(Rect(40, 40, 200, 44), "Invite"): p = net.invite()
        pasted = hud_text_field(Rect(40, 100, 700, 44), pasted, "code", 400, "or their code here")
        if hud_button(Rect(40, 160, 200, 44), "Join") and net.code_kind(pasted) == "invite": p = net.join_invite(pasted)
        return
    text("Send them: {mine}", vec2(40, 40), 16)          # (and set_clipboard(mine), or a Copy button)
    if net.code_kind(mine) == "invite":
        pasted = hud_text_field(Rect(40, 100, 700, 44), pasted, "reply", 400, "their reply here")
        if hud_button(Rect(40, 160, 200, 44), "Connect"): net.accept_reply(p, pasted)

**The screens, ready made: import invite.** Invite a friend shows a link to send (it opens the game in a browser: the page's own address in a web page, the web_page given on a computer), with Copy and, on phones, Share; Join a friend takes a pasted link or code (a Paste button on a phone) and shows the reply to send back; both say why when nothing connected, and Back leaves. A game's menu opens them, and draw shows them until the friend is connected:

import net
import invite

friend = -1
invite.from_link()                      # opened from an invite link: Join a friend, at once
draw = ():
    global friend
    if invite.active():
        if let c = invite.screen("My Game", "https://example.com/mygame/"):
            friend = c.peer             # connected; c.inviter: this side invited
        return
    ...
    if ui_button("Invite a friend"): invite.start()
    if ui_button("Join a friend"): invite.join()

Until the friend is connected, net.receive() leaves their events to the screens; after that, everything from them is the game's. examples/duel and examples/netpong use them, and sloppy new my_game online starts from a small game that does (two players, rollback, a practice mode).

Netpong's Invite a friend and Join a friend show the whole of it, with the codes copied to the clipboard and pasted back.

Rooms: a matchmaking server instead of the reply code. With invite.server(url) (a server of your own, tools/rendezvous.jo: how to run one), Invite a friend opens this computer's room instead: a short code ("KX7P4") and a link with it (?room=KX7P4), kept, so they are the same after a refresh or a restart (New code makes another). Friends type the code into Join a friend, or open the link, and nothing comes back: their game and the host's pass the invite and the reply through the server, and then connect straight to each other as before. A friend who comes while the host's game is not open is told so, and joins once it is. The screen keeps Invite with a code instead, and says so when the server cannot be reached.

invite.server("wss://match.example.org")        # (web pages and native builds alike)
invite.from_link()                              # (?room=... too)
...
if ui_button("Invite friends"): invite.start(players = 4)      # a room for 4, this side too

A room lets in several friends, one by one: the first comes from invite.screen as before, the others from invite.arrivals() (each frame, in the game's lobby); invite.room_busy(true) makes those who come wait, told why, while a fight is on; invite.room_code() is the code to show in a lobby, and invite.close_room() closes it. SLOPPY_SERVER (a page's ?server=) points any game that uses import invite at a server, for trying one; examples/aces uses rooms.

A game with a lobby of its own opens the room with invite.open_room() instead: no screen, the lobby shows room_code() (big, to read out), room_link(web_page) and room_status() (which also says why it could not open), and friends come by arrivals(). invite.start_codes() is Invite with a code instead, from the lobby's own button.

Play with anybody. invite.anybody() asks the server for a public room of the game: one with space (whose host is not busy), or, when there is none, a new one this side hosts. Its screen says how it goes, and gives the host Invited(-1, true) at once (nobody yet: the others come by arrivals(), as to a room), and the others the host, as Join a friend does. A host's room_busy(true) (a fight on) sends those who come to another room; one waiting in a public room whose host leaves is found another. Aces starts a public room's fight by itself after 30 s, the computer filling the sides, so nobody waits long for a full room.

A browser with WebRTC turned off (Firefox's media.peerconnection.enabled = false, a privacy setting; some privacy extensions) cannot connect to anyone. net.webrtc_missing() says so, in words for players ("" where WebRTC works, and always in native programs); net.invite and net.join_invite then fail with it as net.why, and every one of the invite screens shows it (with how to turn it on in Firefox) instead of trying.

Aces's lobby shows both sides, the same on every player's screen: the host keeps each player's side, and sends the sides (who flies which plane, their names and insignias) to everyone twice a second; a friend's Switch side asks the host, which moves them if that side has room. Plane i is on side i % 2, so the players on each side take its planes in order and the computer the rest. A name or insignia changed during a fight goes to the host, which tells everyone: it is only drawn, never part of the game the tick plays.

What players need to know, a game should show them: the host's screen gives its address, net.local_address() (as 192.168.1.20), and the one joining types it; both on the same network (the same Wi-Fi or router), and on one computer, localhost. examples/netpong does this, with a "How to play together" screen. Over the internet, the host's router has to pass the port on to it (port forwarding), or both connect to a server with a public address.

A web page cannot listen, and a page served over https (as from a website) may only reach wss:// servers or localhost; native builds reach wss:// servers too (TLS, with the server's certificate checked against the authorities the system trusts). For trying a game with pages alone, tools/netpong_relay.py (Python, no Sloppy needed) serves Netpong's page over plain http on the network and passes messages between two pages, the first of which hosts: a pattern for any game's own relay.

Matching game builds

Rollback sessions, clients and servers have a version: str field. Before play starts they exchange it, independently of the game's input and world types. A mismatch stops rollback at tick zero, with s.problem such as player 2 runs a different build of this game (theirs: 1.3, this one: 1.4). A client sets c.problem and stays disconnected; a server rejects the connection and reports (peer, reason) in srv.errors after its next update, without adding a player. A rollback input forwarder reports the incompatible build to its other clients too; a machine supplying stand_in inputs vouches for their build, including at startup. The checks apply over manual transports, UDP, net peers, relay fallback and direct WebRTC alike.

The default is PROGRAM_BUILD_ID, a compiler-provided source identity. It hashes the sources read for the program, including imports and the standard library, with their logical module paths (independent of checkout and cache directories). The same sources give the same identity in native and web builds, debug and release; changing even a comment changes it. It is a quick mismatch detector, not a signature. External assets and foreign code are outside it. Different entry files, or target-specific imports, can give different IDs even for compatible programs.

Set an explicit shared release name before the first play, join, listen or connect when client and server have different entry files, or when managing compatibility deliberately:

s.version = "1.4"                # rollback, on every player's session
srv.version = "1.4"              # client-server: both programs use the same name
c.version = "1.4"

An explicit version replaces the automatic identity: bump it when incompatible code, assets or wire formats change. Keep it fixed for the lifetime of a session/server/client connection. This protocol requires both games to use the updated library; older protocols are rejected with a handshake/packet error.

Rollback

Every machine runs the whole game from the same start, and only the inputs travel. A remote input that has not arrived when its tick comes is predicted (the player's last input, repeated); when it arrives and was different, the game goes back to that tick and plays the ticks since again, which with Sloppy's value semantics is a copy of the game kept for each tick.

import netplay

struct Pad:                             # one player's input for one tick
    x = 0
    fire = false
struct Game:                            # everything play depends on
    score = 0
tick = (g: Game, pads: Pad[]) -> Game:  # one tick of play (the same for the same inputs)
    g

s = netplay.session(Game(), tick, players = 2, me = to_int(env("PLAYER") ?? "0") ?? 0)
s.udp(4400 + s.me, [("192.168.1.20", 4400), ("192.168.1.21", 4401)]).unwrap()

Then once a tick, s.play(pad) with this machine's input, and draw s.state.

With invite codes, and no server. s.over(peers) plays over peers from net: peers[p] is player p's, and this machine's own entry is not used. With invite codes (see Messages above), two players connect straight to each other from web pages and native programs alike:

# player 0 invites; the packets may be lost (newer ones carry the same inputs again)
friend = net.invite(reliable = false)
s = netplay.session(Game(), tick, players = 2, me = 0)
s.over([-1, friend])
# player 1, with the code: host = net.join_invite(code) ... s.over([host, -1])

For more players, one hosts: it invites each of the others (an invite and a reply each), tells each its number in a message of the game's ("you are 2"), and plays over all of them, s.over([-1, a, b]); the others play over the host alone, s.over([host, -1, -1]), and the host combines what goes between them (tests/net/np_three.jo does this; Aces does it for up to twelve, in examples/aces). Each client sends one packet to the host per play call, with its own inputs and one receipt per player. The host sends one packet to each connected peer, combining the input ranges that peer has not acknowledged, including any stand-ins. Each range resends up to 64 recent inputs, so a lost packet is covered by the next; a slow peer does not increase anyone else's input range. A peer whose transport backlog exceeds 16,000 bytes skips a packet until it can take more.

The host's packet count grows with the number of peers. Each packet has one receipt vector and one timing/hash header, with timing and inputs for the players it forwards. Input text is serialized once per source and tick, shared across recipients. The host still has to deliver each player's inputs to every other player: total input bytes can grow quadratically with the player count, even though packets grow linearly and each packet's metadata grows only linearly. Full mesh connections, including UDP, continue to send directly per pair.

For a reproducible transport-only measurement without a game or sockets, build and run tools/rollback_load.jo with the player count and frame count as arguments. It reports host and client packets and payload bytes per tick after warming up.

When a player leaves, the session would wait for their inputs. s.stand_in(p, input) has this machine play for them from then on: their inputs that reached it are kept, and input is theirs for every tick after, sent to the others as theirs. A game makes that input mean "the computer flies it" (a field the tick reads). Only a machine that had everything the leaver sent anyone can do it: the host (all of it passed through the host), or either of two players. A page that closes may not be reported as gone for half a minute: a player s.silent(p) for some seconds can be taken as gone (Aces waits 8), but only while the game lasts: after it, a player reading the results, or back in the lobby, plays no more ticks and sends nothing.

The session's packets on those peers are its own (marked, so the game's net.receive() leaves them); the game sends and reads its own messages on the same peers as ever (a chat, "again?"), and their .joined and .left are the game's, to say "connected" or "your friend left". Until the other players' build handshakes match, the session holds at tick zero (s.waiting); inputs made while waiting are kept for when play starts.

The tick must come out the same on every machine. Sloppy's math is its own (no system math library, no fused multiply-add), so the same code gives the same numbers on Linux, Windows, macOS and in a web page. What breaks it is the game reading something that differs between machines:

The compiler warns where the tick given to netplay.session, or a function of the program's it calls, takes random numbers, reads the clock or the input, or changes a global. (An Rng kept in the game, g.rng.next_float(), is the same everywhere.)

A tick may be played several times (each rollback plays it again), so it must do nothing but compute the game: a sound or particles started in it would start again. Start them in update from what changed in s.state since the last frame.

s.ping_ms(p) is the round trip to player p and back, in milliseconds, to show players (a client's is c.ping_ms). It is from an input made to the answer's arrival, so it includes the frame each side waits before it plays and sends: two machines on one computer show about 16 ms.

When it does break, the session finds out: each machine sends a hash of its game at ticks that everyone's inputs are in for, and s.desync says the first tick at which two differed. That, and other trouble (packets from another build of the game that cannot be read, two machines with the same me, a player not heard from for 5 seconds), is in s.problem and said once on stderr. A debug build (not --release) also writes its game at that tick, as JSON, to netplay-desync-<tick>-p<me>.json: the two machines' files differ where the games went apart. Test with a different SLOPPY_SEED for each machine: screenshot runs (SLOPPY_SCREENSHOT) seed random() alike and step by exactly 1/60 s, which hides those two mistakes.

Input delay. An input takes effect delay ticks after it is made (2 by default, about 33 ms), which hides that much latency with no rollback at all. More delay means fewer and shorter rollbacks; fighting games use 2 or 3, and more for a far player: about half the ping in ticks, s.delay = clamp(int(s.ping_ms(other) / 2.0 / 16.7), 2, 6). s.delay may be changed at any time (from the ping once it is known, or a setting): a longer delay gives the ticks between the same input, a shorter one plays the inputs made meanwhile in turn.

Waiting. A session runs at most s.max_ahead ticks ahead of the inputs it has (10; then s.waiting is true and the game holds still), and slows down a little when its clock is ahead of the other's, so both keep pace. Set it after making the session, as delay. Inputs made while it waits are not lost: each change of input is played in turn on the ticks after (a button tapped during a wait still hits).

A machine that stops for a moment (a 0.3 s hitch: a disk, another program) catches up on the ticks it missed only as far as dt goes, which is never more than 0.1 s (a game playing a tick for each 1/60 s of it); the rest of the time is lost, and the others, who went on, wait a few frames for it and then run a little slower until both agree again.

Replays and spectators. The ticks below s.confirmed() have everyone's inputs for good, and s.inputs_at(t) gives them; taken as they come, they are a replay: the game played again from its start, tick by tick, comes out the same (and the same on another machine, so a spectator can be sent them).

saved = 0
replay: Pad[][]
update = (dt: f64):
    s.play(read_pad())
    loop saved < s.confirmed():
        replay.push(s.inputs_at(saved))
        saved += 1

Played again: g = Game(), then loop pads in replay: g = tick(g, pads). A desync shows up here too: two machines' replays are the same inputs, and the tick at which their games differ can be found by playing each.

A spectator is sent them as they come. The game sends s.feed(sent) (the inputs confirmed since sent) to the spectator over any transport, its own net.send included, and the spectator plays them with a Watch, about 0.1 s behind the players. A spectator who comes in late is sent s.feed(-1) first: the game as it is at a confirmed tick, then the inputs from there.

# a player's machine
sent = -1
update = (dt: f64):
    global sent
    s.play(read_pad())
    net.send(viewer, s.feed(sent))
    sent = s.confirmed()

On the spectator's machine, use its own game-loop callbacks:

w = netplay.watch(Game(), tick)
update = (dt: f64):
    loop m in net.receive(): w.receive(m.data)
    w.update(dt)
draw = (): text("{w.state}", vec2(20, 20))   # replace with drawing the spectator's world

w.waiting is true while the feed has not caught up (the game holds still until w.behind ticks, 6, are in hand), and w.problem says what is wrong with a feed: one from another build of the game, or ticks skipped.

Local players. Two players on one keyboard, or a keyboard and a gamepad, give each player actions of their own, declared for their number: action("p2 punch", [.key(.k), .button(.x)], player = 1) is the K key, and gamepad 1's X.

Rollback players who restart

A player whose program restarts (a page reloaded, a crash) can come back into a running game. Every player's session takes part, before its first play:

s = netplay.session(Game(), tick, players = 3, me = me)
s.over(peers)                                   # (or s.join_relay(...))
s.allow_rejoin(load_data("rejoin") ?? "")       # "" for a player new to the game
# after each s.play(...): the token this player was given, kept for a restart
if s.rejoin_token != saved:
    saved = s.rejoin_token
    save_data("rejoin", saved)

One machine keeps each player's place: the host the others play over, or in a mesh (a relay room, two players over invite codes) player 0, and player 1 for player 0. It gives each player a 256-bit random token, s.rejoin_token, sent again until it arrives. A program that starts again makes its session as before (the same players and me: save me beside the token, and the room) and passes the saved token to allow_rejoin. Then:

  1. It asks the host (s.rejoining and s.waiting are true until it plays again: draw "coming back..."). The host checks the build, then the token, before anything of the game is sent; if it was not already playing for that player (stand_in), it starts now, with no input.
  2. The host sends the game at the latest tick every input is in for, K = min(s.confirmed(), s.tick), as its text (to_text), deflated, in pieces, then every player's inputs from K on. The returning machine plays them as fast as a few milliseconds a frame allow.
  3. Once it has caught up, the host chooses a tick about half a second on and tells it. Below that tick the host's stand-in inputs are the player's, everywhere; from it on, the returning machine's own. The new process's packets carry a newer epoch, so anything late from its old process is left; its connection replaces the old one (a relay retires the old one).
  4. When the returning machine has everything below that tick it says so, and plays. On the host, s.rejoined lists the player for that play, and s.stands_in(p) is false again.

The others never wait for it: meanwhile the host plays for the absent player, and keeps every input since K for the returning one (for up to a minute of play; one that falls further behind, or stops answering, is sent a newer game, and after four tries is refused). One that stops again during all of this is played for as before, and may ask again with the same token. A host that hears nothing from it for 5 seconds gives up on it (a page in the background, say); a returning machine that hears nothing from the host for as long asks again, for a newer game.

Over net's peers (s.over), the returning program connects to the host again in whatever way the game connects (listen and connect, or a new invite code), and the host gives the new connection to the session: s.admit(peer), for example on each .joined of a game that listens. Its token says which player it is, and the session plays over it in that player's place from then on. Call after allow_rejoin. An admitted peer that sends no valid rejoin request within ten seconds is closed; s.admit(peer, timeout = 20.0) changes that deadline. s.admit_expired lists the peer IDs closed for this reason in the latest s.play (read it after each call, as with s.rejoined). Re-admitting a pending peer does not extend its time; 0 expires on the next play. Peers already accepted as returning players use the normal transfer timeout instead. Through a relay, the returning program joins the same room as before, and nothing more is needed; web pages connect straight to it again (WebRTC). Without a transport of the session's own (s.outgoing()/s.receive()), deliver its messages to that player as any others. Rejoining's messages go on the session's connections, never UDP: each is sent again until it is acknowledged, so a lost one only delays it. A session over s.udp cannot come back (its problem says so), and its host refuses one that asks.

A refused player's session holds still, with s.problem saying why: a token that is wrong or has expired, another build, a game too large, one that could not catch up. Its game decides what next (a new session, back to the menu). Settings, before play:

The returning session starts at tick K, not 0: s.inputs_at has the ticks from K on (a replay kept from the start begins again after a return), and its game must come back the same from its text, as it does for a spectator's feed(-1): plain data, with nothing the tick reads kept elsewhere. The host's own restart, in a game that plays over a host, is not one it can come back from: the others have no one to play over.

s.rejoined is for one play: a frame that plays several ticks (as below) reads it after each s.play, or misses it.

s.heard(p) says whether a player has sent a packet yet (directly or through the host). Before using silence to stand in, check s.heard(p) and s.silent(p) > 3.0: a friend's page may still be loading. s.silent(p) keeps its original clock, from session start until the first packet, then from the last packet. Use it alone when the initial connection should also have a deadline. Your own player is always heard.

sloppy new mygame room makes a small coin race using this pattern: two to four players, room links, rollback and guests rejoining after a reload. sloppy build mygame/mygame.jo --target wasm builds its web page; set WEB_PAGE in the source for native hosts' links. It uses the public matchmaking server by default; SLOPPY_SERVER selects your own.

A matchmaking server's room (invite.open_room, above) gives the host a link to send; each friend who opens it is connected straight to the host, and the host numbers them and starts the session over them. A friend whose page reloads opens the same link again and comes back into the game: the host admits the new connection, and the friend's session takes its saved token. The whole of it, in a program (examples/aces does the same for twelve):

import net
import netplay
import invite

struct Pad:
    x = 0
struct Game:
    pos: int[]
tick = (g: Game, pads: Pad[]) -> Game:
    let g = g
    loop i in 0.. and p in pads: g.pos[i] += p.x
    g

invite.server("wss://match.example.org")
invite.from_link()                              # (a friend opened the room's link: ?room=KX7P4)
room = env("ROOM") ?? ""                        # (that link's room: a page's ?room=)
hosting = false
guests: int[]                                   # (the host's: players 1, 2 and 3)
host = -1                                       # (a friend's: the host's peer)
s = netplay.session(Game(), tick, players = 2, me = 0)
playing = false
token = ""

play_as = (me: int, players: int, saved: str):
    global s, playing, token
    s = netplay.session(Game(pos = fill(0, players)), tick, players = players, me = me)
    peers = fill(-1, players)
    if hosting:
        loop i in 0.. and p in guests: peers[i + 1] = p
    else: peers[0] = host
    s.over(peers)
    s.allow_rejoin(saved)
    token = saved
    playing = true

update = (dt: f64):
    global token
    if hosting:
        loop c in invite.arrivals():
            if playing: s.admit(c.peer)         # (a friend coming back after a reload)
            else: guests.push(c.peer)
    loop e in net.receive():
        if e.kind == .message and starts_with(e.text, "start "):
            w = split(e.text, " ")
            play_as(to_int(w[1]) ?? 1, to_int(w[2]) ?? 2, "")
    if not playing: return
    s.play(Pad(int(input_axis().x)))            # (once a tick: see Ticks, not frames)
    if s.rejoin_token != token:                 # (kept with the room and the player's number)
        token = s.rejoin_token
        save_data("rejoin", "{room} {s.me} {s.players} {token}")
    if s.me == 0:                               # (the host plays for a friend gone quiet)
        loop p in [1..s.players):
            if not s.stands_in(p) and s.heard(p) and s.silent(p) > 3.0: s.stand_in(p, Pad())

draw = ():
    global hosting, host
    clear()
    if invite.active():                         # a friend, connecting to the host
        if let c = invite.screen("My Game"):
            host = c.peer
            w = split(load_data("rejoin") ?? "", " ")
            if w.len() == 4 and w[0] == room:   # (this page was reloaded during a game)
                play_as(to_int(w[1]) ?? 1, to_int(w[2]) ?? 2, w[3])
        return
    if playing:
        loop i in 0.. and x in s.state.pos: circle(vec2(640 + x, 200 + i * 80), 20, WHITE)
        if s.rejoining: text("coming back...", vec2(20, 20), 24)
    else if not hosting:
        if hud_button(Rect(40, 40, 200, 44), "Host a room"):
            hosting = true
            invite.open_room(reliable = false)
    else:
        text("Room {invite.room_code()}: {invite.room_link()}", vec2(40, 40), 20)
        if guests.len() > 0 and hud_button(Rect(40, 100, 200, 44), "Start"):
            loop i in 0.. and p in guests: net.send(p, "start {i + 1} {guests.len() + 1}")
            play_as(0, guests.len() + 1, "")

The room stays open through the game, for those who come back: open_room(players = n) would close it once n are in, and room_busy(true) would make them wait until it is off. So the game keeps the count of players itself (the lobby turns away a fifth: net.close). A friend who comes while the game is on and is not coming back is admitted too, but has no token or place. The session closes the connection after the admission timeout (ten seconds by default) and lists it in s.admit_expired. A game that wants newcomers to watch, or to wait for the next round, tells them apart itself (by a message of its own from a friend who has nothing saved). Forget the saved token when the game ends (delete_data), so a later visit to the link joins the lobby as new.

Rooms are on the matchmaking server (tools/rendezvous.jo), which passes only the codes that connect the games: the games' packets go straight between them. A relay (netplay.relay, s.join_relay, below) is another way, which passes every packet; it needs no matchmaking server, but players there choose their own numbers.

Client and server

The server runs the game; clients send their inputs and draw the worlds it sends back. Three things hide the latency:

import netplay

apply = (w: World, player: int, input: Pad, seen: World) -> World: w    # one player's input
step = (w: World) -> World: w                                          # the rest of a tick

srv = netplay.server(World(), apply, step)      # (a native program)
srv.listen(4600).unwrap()                                # once a tick: srv.update(); srv.joined, srv.left

c = netplay.client(World(), apply)
c.connect("game.example.com", 4600)             # once a tick: c.play(pad); draw c.state and c.view()

If the server and client are built from different entry files, set srv.version = "1.4" and c.version = "1.4" before listening/connecting. The automatic source identities otherwise differ; see matching game builds.

The server's world is the truth: a client cannot move its player anywhere its inputs would not take it there, and the server applies at most one input of each player a tick (a few more after a pause, to catch up), so sending more moves no faster. The game need not be deterministic.

A client predicts with apply only: what moves a player belongs in apply (in step, the client's own player would wait for the server). random() in apply makes the client's guess and the server's differ, which shows as flicker: draw it from something both have. Add each player to the world when srv.joined names them, and take them out on srv.left. c.connected() turns false, and c.problem says why, when the client cannot connect, the server closes the connection (with its reason: net.close(p, 4001, "the room is full") on the server), or nothing comes from it for 5 seconds. With c.reconnect = true a client connects again by itself when the connection is lost or the server goes away or restarts (after 1, 2, 4... up to 30 seconds), not when the server closed it on purpose. With the default srv.rejoin_grace = 0.0, that joins a new player with the same hello; with a grace period it restores the previous player, as below. A server without a window calls srv.run(): srv.update() 60 times a second, on time (a loop of update and sleep(1.0 / 60.0) ticks a little slower than the clients, and their inputs wait in a queue: lag).

srv = netplay.server(World(), apply, step)
srv.listen(4600).unwrap()
srv.run()                       # (or each tick in a game's own update: srv.update())

What a player is called goes with the connection: c.connect(host, 4600, hello = name), and the server reads srv.hello(p), available when srv.joined reports the accepted player. Hello is game metadata; rejoining uses a separate server-issued token. c.disconnect() closes the connection; c.connect(...) opens another.

The game's own messages (a chat line, "round over", the scores) go on the same connection, as text, in order: srv.say(p, text) to one player, srv.say_all(text) to everyone, read by the client in c.messages after each c.play; c.say(text) to the server, read in srv.messages (who sent each, and what) after each srv.update().

To try a slow network on one machine, srv.lag_ms(100, 20) and c.lag_ms(100, 20) hold what each side sends 100 ms, and up to 20 ms more at random (in order, as TCP keeps it). srv.waiting(p) says how many of p's inputs wait to be applied: 1 or 2 is right; more is lag.

The world goes to every client as its text (to_text), compressed, every srv.send_every ticks (2: 30 a second): a few hundred bytes for a small arena. Keep what does not need to travel (effects, sounds) out of it, or in the client only. A big world (a hundred players, an army each) goes out in parts: srv.per_player((w: World, p: int) -> World: ...) gives each player the world as that player should see it (the soldiers near them, their side's), and is what that client's state and view() then hold. srv.compress = false sends the worlds as text, not deflated: cheaper for the server to make, when its bandwidth is not what is short. For the fewest bytes, the game writes the worlds itself, each against the last one that client has: srv.encoding((w: World, p: int, base: World?) -> u8[]: ...) on the server and c.decoding((data: u8[], base: World?) -> World: ...) on the client, where base is the same world on both sides (none for the first, or after a client fell far behind). Only what changed since base need go (the soldiers that moved, as varints), and nothing is turned into text or deflated; with per_player, w is that player's part. tests/t/netplay_encoding.jo has one. A client still behind on the worlds before (a slow link) is not sent the next one until it has caught up: a newer one replaces it. A screenshot run (SLOPPY_SCREENSHOT) of a connected client keeps to real time, as the server does.

Bullets and other things moved in step are not predicted: the client sees them when the server's world shows them, half a round trip and the interpolation later. For a shot that must show at once, draw its flash in the client when the button is pressed, and let the server's world bring the bullet.

Rejoining after a drop or restart

Set srv.rejoin_grace before the first join to the seconds a disconnected player may return (0 by default, which keeps immediate departures). With grace, srv.dropped reports that a player lost its connection; their number and the game's srv.world entry stay in place. srv.rejoined reports their return. srv.left reports the final departure when the grace period expires, once. All four event lists are for the latest srv.update(); only fresh, accepted players appear in srv.joined.

srv.rejoin_grace = 30.0
# after each srv.update():
loop p in srv.joined: srv.world.pos[p] = 0
loop p in srv.dropped: print("player {p} disconnected; holding their place")
loop p in srv.rejoined: print("player {p} is back")
loop p in srv.left: srv.world.pos.remove(p)

The world keeps ticking during the absence. No queued or new inputs are applied for the dropped player: the game decides whether to leave them still, run an AI, pause a round, or show them as a ghost. Only remove their state on left, and do not reset it on rejoined. Grace is measured in elapsed seconds, independently of server tick rate. srv.errors contains (transport_peer, reason) for rejected joins (bad build, bad/expired token, or a handshake not completed within five seconds).

The server issues a 256-bit random token with the first accepted join when grace is enabled. c.rejoin_token: str exposes it; the same Client keeps and offers it automatically on reconnect, including with c.reconnect = true. For a program restart, save it and restore it before connecting:

c.rejoin_token = load_data("room-token") ?? ""    # save separately for each server and room
c.connect(host, 4600, hello = name)
# after connecting, when c.rejoin_token changes:
save_data("room-token", c.rejoin_token)

load_data/save_data use the program's save folder on native and browser storage in a web page. A token is a bearer credential: keep it private, use wss:// across untrusted networks, and never send it through chat/hello or log it. A wrong, expired or unknown token is rejected, never silently turned into a new player. Clear c.rejoin_token = "" before connecting to start fresh, use a different room/server, or after the server itself restarts and loses its in-memory players. A valid token can also replace a stale connection before the server detects its loss: the old connection receives a reason and closes (4003), and its inputs no longer apply. That handover reports both dropped and rejoined. Otherwise grace starts when the transport reports the old connection gone (loss detection can take a few seconds). Explicit disconnect also retains the place for the grace period. For an immediate final departure, call srv.leave(peer, rejoin = false): it revokes the token and reports left. A listening game also closes that transport itself, for example:

if let peer = srv.peer(p):
    srv.leave(peer, rejoin = false)
    net.close(peer, 4001, "left the game")

A returning connection keeps the same c.me and server world entry. Prediction queues, input sequence numbers, interpolation history and delta bases start fresh; the first encoded world uses base = none. Unapplied inputs queued before disconnection and inputs made while away are discarded; previously applied inputs remain part of the authoritative world. Per-player views, compression and custom encoding apply as before. Transient game messages are not replayed across a rejoin.

Player numbers and transport peers can differ after rejoining. srv.say(p, ...), hello(p), waiting(p), views, encoders, inputs and events use the stable player number. srv.peer(p) -> int? returns its current transport connection, or none while dropped: close it with if let peer = srv.peer(p): net.close(peer, 4001, "bye"). For servers fed by hand, join(peer), receive(peer, bytes), leave(peer) and outgoing() continue to use transport peer IDs. Forward every handshake packet in both directions, even before c.connected() is true. A server fed by hand emits a terminal tag 7 for a rejected/displaced connection; forward it and close that transport yourself. A listening server closes it automatically.

Other tick rates

A game that needs fewer ticks (a strategy game, a slow arena: 20 or 30 a second) or more (up to 120) says so on the server: srv.run(20), or srv.ticks_per_second = 20 for a server ticking in its own loop. The worlds carry it to the clients (c.ticks_per_second), and each client calls c.play once a tick at that rate (as below, with 1.0 / c.ticks_per_second for 1.0 / 60.0). c.view() is meant to be drawn every frame: between two plays it goes on by the time since the last, so others move smoothly at 60 frames a second with a server at 20. c.interpolation is in seconds: at least the time between two worlds (srv.send_every ticks: srv.send_every = 1 at 20 a second), and more on an uneven network.

The host plays too

A game whose host is also a player runs the server and a client of its own in one program, without a connection between them: the host's player is a number below 0 (the network's are 1 and up), joined and fed by hand while the server listens for the others.

srv = netplay.server(World(), apply, step)
srv.listen(4600).unwrap()
srv.join(-1)                            # the host's own player
me = netplay.client(World(), apply)     # (not connected: fed by hand)

update = (dt: f64):                     # (once a tick)
    srv.update()
    loop o in srv.outgoing(): me.receive(o.1)         # (what the server has for -1)
    if me.connected(): me.play(read_pad())
    loop b in me.outgoing(): srv.receive(-1, b)

The host's player is as any other to the server (srv.joined, srv.hello, srv.say); its worlds come at once, so it plays with no lag. More than one player at the host's screen (a split screen) take -1, -2 and so on, each with a client of its own.

Several games on one port

One server can hold many games, each a netplay.server of its own, behind one http server on one port (its pages, its API and the games' WebSockets together). Without srv.listen, a server is fed by hand: srv.join(p), srv.receive(p, data) and srv.leave(p) from the program's own net.receive_server() loop, and what it has to send comes from srv.outgoing():

import http
import net
import netplay

rooms: {str: netplay.Server[World, Pad]}       # a game each, by its name
room_of: {int: str}                             # each player's room

http.get("/play/:room", (r: http.Request) -> http.Response: http.websocket(r))
http.files("/", "public")
http.listen(8080)
next = time()
loop not stopping():
    http.answer()
    loop e in net.receive_server():
        if e.kind == .joined:
            name = net.handshake(e.peer).path[len("/play/")..]
            if not rooms.contains(name): rooms[name] = netplay.server(World(), apply, step)
            if [loop _, r in room_of: if r == name: r].len() >= 8:
                net.close(e.peer, 4001, "the room is full")
                continue
            rooms[name].join(e.peer)
            room_of[e.peer] = name
        else if let name = room_of.get(e.peer):
            if e.kind == .message: rooms[name].receive(e.peer, e.data)
            else:
                rooms[name].leave(e.peer)
                room_of.remove(e.peer)
    # (every room's tick, 60 a second, on time)
    if time() >= next:
        next = max(next + 1.0 / 60.0, time() - 0.25)
        loop name in [loop n, _ in rooms: n]:
            rooms[name].update()
            loop p in rooms[name].joined: rooms[name].world.pos[p] = 0
            loop p in rooms[name].left: rooms[name].world.pos.remove(p)
            loop o in rooms[name].outgoing():
                net.send(o.0, o.1)
                if o.1.len() > 0 and o.1[0] == 7: net.close(o.0, 4002, "netplay connection closed")
            peers = [loop _, room in room_of: if room == name: room].len()
            if peers == 0 and rooms[name].world.pos.len() == 0 and rooms[name].tick > 60: rooms.remove(name)
    net.wait(max(next - time(), 0.0))

A client joins a room by its address: c.connect("wss://game.example.com/play/red", 0). A task for each room works too (its server fed through a channel); the loop above is the simplest, and costs no more.

What goes over the wire

For a bot or a client in another language: a WebSocket, binary messages, each starting with a byte that says what it is.

Ticks, not frames

Both kinds play in ticks of 1/60 s (a client-server game at the server's rate: c.ticks_per_second). A screen may show 144 frames a second, or drop a frame, so count ticks apart from frames:

spare = 0.0
update = (dt: f64):
    global spare
    spare = min(spare + dt, 0.1)
    loop spare >= 1.0 / 60.0:
        spare -= 1.0 / 60.0
        s.play(read_pad())

Trying it on one machine

Run the game twice (two windows), as two players on this machine's addresses: examples/duel takes PLAYER=0 and PLAYER=1. A real network is slower and loses things: s.lag_ms(100, 20, 0.05) adds 100 ms (and up to 20 more) to what this session sends and drops 5% of it, and examples/duel takes LAG=100. For tests, netplay.Link is a network simulated in one program, with its own clock: two sessions over it play the same way every time (tests/t/rollback.jo, tests/t/clientserver.jo). Give netplay the same clock each frame, netplay.clock(now), and its own timing (sending again what was lost, how long a player has been quiet, a returning player's grace) goes by it too, so a test needs no sleep and runs as fast as it can (tests/t/rollback_rejoin.jo); without it, that timing is real time (elapsed()).

Here is a complete two-player rollback program for loopback. Save it as local_duel.jo. Each player's dot moves left and right; both machines run the same tick. The copy at the start of tick makes its read-only parameter a local value to change and return.

import netplay

window("Local duel", 640, 360)
struct Pad:
    x = 0
struct Game:
    x: int[] = [160, 480]

tick = (g: Game, pads: Pad[]) -> Game:
    let g = g
    loop p in 0..2: g.x[p] = clamp(g.x[p] + pads[p].x * 2, 20, 620)
    g

s = netplay.session(Game(), tick, players = 2, me = to_int(env("PLAYER") ?? "0") ?? 0)
s.udp(9640 + s.me, [("127.0.0.1", 9640), ("127.0.0.1", 9641)]).unwrap()
spare = 0.0
update = (dt: f64):
    global spare
    spare = min(spare + dt, 0.1)
    loop spare >= 1.0 / 60.0:
        spare -= 1.0 / 60.0
        s.play(Pad(int(key_down(.right)) - int(key_down(.left))))
draw = ():
    clear()
    circle(vec2(s.state.x[0], 140), 18, CYAN)
    circle(vec2(s.state.x[1], 220), 18, ORANGE)

Run PLAYER=0 sloppy local_duel.jo and PLAYER=1 sloppy local_duel.jo in separate terminals. For a headless check, build once with sloppy build local_duel.jo, then run both copies concurrently:

env -u DISPLAY -u WAYLAND_DISPLAY PLAYER=0 SLOPPY_NO_DRAW=1 SLOPPY_NO_AUDIO=1 SLOPPY_FRAMES=300 SLOPPY_INPUT="10:right+ 80:right-" ./local_duel >p0.log 2>&1 &
p0=$!
env -u DISPLAY -u WAYLAND_DISPLAY PLAYER=1 SLOPPY_NO_DRAW=1 SLOPPY_NO_AUDIO=1 SLOPPY_FRAMES=300 SLOPPY_INPUT="10:left+ 80:left-" ./local_duel >p1.log 2>&1 &
p1=$!
wait "$p0"; wait "$p1"

SLOPPY_NO_DRAW=1 skips draw callbacks and frame presentation in native builds, with no window needed. Update, scripted input and the normal frame timing continue; keep networking and simulation in update. For menus that handle clicks in draw, use SLOPPY_SOFTWARE=1 instead. SLOPPY_FIXED_STEP=1 gives exactly 1/60 s per frame with either mode (network sessions still pace in real time); a screenshot request renders even with no-draw set.

Use different SLOPPY_SEED values for a stronger determinism check, and try s.lag_ms(100, 20, 0.05). To compare the games, save confirmed inputs as they arrive (the replay example above), then replay the saved inputs from Game() to the same tick on both sides. Their current s.state values may be at different ticks when each program exits; comparing those can report a false desync. Keep both copies playing until each has confirmed the tick being compared.

Web pages

A web page cannot use UDP or wait for others to connect. It connects over WebSockets to a native program: a client-server game's server, or for rollback, a relay (netplay.relay(port).unwrap(), which a native player can run while playing) that passes packets between the players in a room (s.join_relay(host, port, room); each still gives its own me: the relay does not hand out numbers, and two with the same one are told so). A page served over https can only reach wss:// servers: put a proxy with a certificate (Caddy, for one) in front of the server.

WebSockets run over TCP, where a lost packet holds up those after it. So pages in a rollback room also connect straight to each other with WebRTC: they tell each other how to through the relay, and from then on their packets go between them as over UDP (unordered, never resent, never held up), not through the relay (s.direct(p) says whether player p's do). A STUN server tells each page its address as others see it: join_relay uses Google's public one, and takes stun = "stun:..." for another or "" for none (then only pages on the same network reach each other). Pages that cannot reach each other (some company and phone networks) keep playing through the relay; so does a native player with a page. Relay fallback stays per pair: each packet goes from its sender through the relay server straight to the addressed player. No other player's session forwards it. Direct WebRTC pairs keep exchanging their inputs directly.