ARCANUM
Guide ยท client

The client

A session, the views you ask for, and a prediction of your own player. Aether hands you plain values every frame; drawing and blending stay yours.

What the client does

A client program has one job in each frame: let the SDK talk to the server, then read what it knows. Everything goes through one object, client::Session. You give it a URL, tell it which views you want (the rows of your game, as plain structs), connect, and call poll() from your own loop. The session uses no thread and no lock. Every callback runs inside poll(), on the thread that called it.

This page builds the client of meadow in small steps. It starts with the connection (section 1 to 4), then reads other players (5 and 6), then adds sending, prediction and corrections (7 to 12), and ends with the server clock, reconnecting and the low level. The last section is a reference of every public member.

What the SDK never does on the client: draw, blend two positions, extrapolate, or ease a correction. It gives you the values and the fractions, and you write the one line that uses them.

ClassHeaderWhat it is
client::Sessionaether/client/Session.hOne server connection plus a replica of the views, the typed views, the prediction and the clock. The class you use.
client::TypedView<Row>aether/client/TypedView.hThe rows of one view as a plain struct Row.
client::Prediction<State>aether/client/Prediction.hYour own player, predicted, with the input pipeline.
client::Replicaaether/client/Replica.hThe raw rows of every view, field by field. Below the typed views; no dependency on the server.
client::Connectionaether/client/Connection.hOne WebSocket (or GNS) connection: bytes in, bytes out, reconnect. No game knowledge.
client::ServerClockaether/client/ServerClock.hThe estimate behind session.serverTime().

Include <aether/client.h> and link aether_client. A gns:// URL also needs <aether/client/GameSocket.h> and aether_client_gns (section 15). Next: the session.

1. The session and the poll loop

Start with the smallest client that does anything: connect to a meadow server, and print where your walker is twice a second. The server of meadow is the one from Get started.

examples/meadow/client.cpp
#include <chrono>
#include <cstdio>

#include <aether/client.h>

#include "meadow/Shared.h"

using namespace aether;

int main() {
    client::Session session("ws://localhost:9000/?name=Ayla", {.contract = meadow::contract});
    auto players = session.view<Walker>();   // the rows of the view "Walker"
    session.connect();

    const auto start = std::chrono::steady_clock::now();
    while (std::chrono::steady_clock::now() - start < std::chrono::seconds(4)) {
        session.poll(5);                        // receive, apply, reconcile, send; waits up to 5 ms
        if (session.ready()) {
            if (auto me = players.find(session.me())) std::printf("x=%.1f\n", me->x);
        }
    }
    session.close();
}

Notice four things.

  • view<Walker>() is called before connect(). A view handle is never null: it is empty until the server has described the view, and fills in as rows arrive.
  • poll(5) is the whole engine. It waits up to 5 ms for the socket, does what it can (connect, handshake, read, write, timers, reconnect), applies the messages it read, runs the callbacks, and returns. A negative timeout waits until something happens; 0 does not wait.
  • Nothing is sent or received between two poll() calls. A game that stops polling stops receiving.
  • ready() says "the welcome has arrived and my own row is there" (section 3). Until then session.me() is ecs::kNoEntity and find returns nothing.

The connection is non-blocking: connect() starts it and the rest happens inside poll(). connect() returns false only if the attempt failed at once and no retry is scheduled (onError has said why); it is a no-op returning true if the connection is already Connecting or Open.

Trap: a host name can block. There is no asynchronous resolver. A host name is resolved with getaddrinfo inside connect() and again at each retry, which can block the thread. Give an IP address (or localhost) to avoid it.

URL forms

The constructor takes a URL. client::Options::fromUrl parses it, and the session constructor Session(url, overrides) puts the parsed host, port, path and transport over the connection options of overrides (everything else in overrides is kept).

FormResult
ws://hostPort 80, path /.
ws://host:9000/world?token=abcPort 9000, path /world?token=abc: the path includes the query. The server reads the query with p.query("token").
ws://host:9000?name=AylaA query with no path: the path becomes /?name=Ayla.
ws://[::1]:9000/An IPv6 address in brackets.
gns://host:27015/?name=annGameNetworkingSockets. The port is required; the query is sent as the hello message (section 15). Sets transport = Transport::GameSocket.
wss://...Refused: std::invalid_argument ("TLS is not supported (it is terminated in front of the server); use ws://").
anything else, an empty host, a bad portstd::invalid_argument whose text starts aether::client::Options::fromUrl: , with the reason and the URL.

The port must be 1 to 65535. A gns:// URL without a port throws "a gns:// URL needs a port (gns://host:27015/)".

The other constructor

When you need more than a URL, fill a SessionOptions (section 2) and give it to Session(SessionOptions). The two forms are equal: the URL form is fromUrl plus overrides.

client::SessionOptions options;
options.connection = client::Options::fromUrl("ws://localhost:9000/?name=Ayla");
options.connection.reconnect = true;     // section 4
options.contract = meadow::contract;     // section 14

client::Session session(options);

The session owns a Connection and a Replica that live as long as it does, and you can reach both (session.connection(), session.replica(), section 15). A Session is not copyable. It is one thread: the caller's.

Closing

session.close(code = 1000, reason = {}) starts the close handshake. The state stays Open, and connection().closing() is true, until the server's close frame arrives or closeTimeoutMs (default 1000 ms) runs out; keep calling poll() until session.connection().state() == client::State::Closed. The code is 1000 or 3000 to 4999; the reason is at most 123 bytes. Called while the connection is still Connecting (or waiting to reconnect) it just stops, with no callback.

Next: the options that shape a session.

2. SessionOptions and Options

SessionOptions is what the session itself needs; the nested client::Options is what the connection needs. Every field has a default that works against a server started with server::App app(world).

SessionOptions fieldTypeDefaultMeaning
connectionclient::Optionssee belowHost, port, path, reconnect, limits.
replicaReplicaOptionstickType 2, subscribeType 3, ignoreType 4, dontKnowType 5, layoutType 6, reserve 1024The message types of the server's interest policy. Change them only if the server changed its InterestPolicy types.
clearOnOpenbooltrueClear the replica (rows and the don't-know bookkeeping) when a connection opens. The views stay described. Turn it off only if you manage stale rows yourself.
closeOnMalformedboolfalseClose the connection with code 1002 ("malformed message") when the replica refuses a message.
contractaether::ContractnoneThe contract of your .aether file. Sent in the connect query; a server built from another version refuses you (section 14).
maxBytesPerSecondstd::uint32_t0For a player on a metered or weak link: the most bytes a second you want the server to send. 0 sends nothing. The server does not enforce it; it arrives as p.link().limit for the game's rules (see Network).

The contract and maxBytesPerSecond travel as query parameters appended to the connection's path (? or &): contract=<16 hex digits>&schema=<file name> and maxBytesPerSecond=<n>. Over GNS the same text is sent as the hello.

client::Options, in groups

The complete table, with ranges and what a bad value does, is in the reference. In short:

  • Where: host (the IPv4 loopback address), port (9000), path ("/"), headers, transport. Easiest set with Options::fromUrl.
  • Reconnect: reconnect (false), reconnectMinMs 250, reconnectMaxMs 8000, reconnectFactor 2.0, reconnectJitter 0.2, maxReconnectAttempts 0 (never give up).
  • Pings: answerPings true, answerWebSocketPings true, deliverPings false, interpolationMs 0.
  • Limits: maxMessageBytes 1 MiB, maxQueueBytes 1 MiB, connectTimeoutMs 5000, closeTimeoutMs 1000, idleTimeoutMs 0.
  • Socket: tcpNoDelay true, readChunkBytes 64 KiB, maxReadsPerPoll 16.

Options::validate() runs in the Connection constructor and throws std::invalid_argument naming the field (aether::client::Options::reconnectMinMs: must be at least 1) for a value that can never work.

Next: how to know the session is in the game.

3. Knowing you are in the game

"The socket is open" and "I can play" are different moments. The server sends, in this order, a welcome (your entity, its tick rate, its input rate), the table of message ids, the layouts of the views, and then the first rows. Three accessors tell you where you are.

CallTrue or valid when
connected()The connection is Open and not closing.
welcomed()inputRate() > 0: the welcome has arrived on this connection.
ready()Open, welcomed, and your own row is in one of the views (replica().has(view, me()) for some view). A session whose welcome names no entity (me() == ecs::kNoEntity, a spectator) is ready as soon as it is welcomed.

me(), tickRate() and inputRate() are kNoEntity / 0 until the welcome arrives, and again after a reconnect until the new welcome. The welcome is sent again when the server assigns your player a new entity (a respawn), so me() follows it.

onReady(fn) runs once per connection, inside poll(), at the first poll after ready() becomes true. It is the place for work that needs your entity.

session.onReady([&] {
    std::printf("in the game as %llu, server ticks %d Hz, input %d Hz\n",
                (unsigned long long)static_cast<std::uint64_t>(session.me()),
                session.tickRate(), session.inputRate());
});

Setting onReady replaces the previous function. The input rate is the number of input steps a second the server applies; tickRate() is its world ticks a second. If the server sent an input rate of 0, the client takes the tick rate for it.

Next: what comes back to you as events.

4. Callbacks, errors and close codes

The session has five callbacks. Each takes one function and setting it again replaces it. All run inside poll(), connect() or close() on your thread. A callback may call send, close, connect and setters; it must not call poll(). After a callback closes the connection, the rest of what had been read from the socket is dropped.

session.onOpen([]  { std::puts("open"); });                       // after the replica was cleared
session.onClose([](std::uint16_t code, std::string_view reason) {
    std::printf("closed %u: %.*s\n", code, int(reason.size()), reason.data());
});
session.onError([](std::string_view what) {
    std::printf("error: %.*s\n", int(what.size()), what.data());
});
session.onWarning([](std::string_view text) {                    // the server dropped messages of yours
    std::printf("slow down: %.*s\n", int(text.size()), text.data());
});
session.onMessage([](std::uint8_t type, std::span<const std::uint8_t> body) {
    std::printf("a message of type %u, %zu bytes\n", type, body.size());   // one the typed handlers did not take
});
CallbackRuns when
onOpen()The handshake is done and the state is Open. Runs after the replica was cleared (if clearOnOpen) and the new connection's bookkeeping was reset.
onClose(code, reason)A connection that had been Open has ended. Not called for an attempt that never opened, nor for close() while Connecting. With reconnect on, the next attempt is already scheduled when it runs.
onError(what)A failed attempt (resolve, connect, timeout, bad handshake: the text says which), a protocol error, a malformed message (empty, or type 0), a message of a plain struct with the wrong size, a view whose layout does not match your struct, a view name the server does not have, a full send queue, a waiting move the server has no handler for. The last connection error text is connection().lastError().
onMessage(type, body)A message that is not the replica's (layouts, ticks), the welcome, the id table, a warning, or one of your on<M> handlers. The body is valid only during the call.
onWarning(text)The server dropped messages of this client because it sent too many (the connection's limit, or the limit of one message type). The text says what the limit is. Slow down; if it goes on the server closes the connection with 4290.

If a mistake of yours must not pass silently (a view name the server does not have, a view whose layout does not match your struct) and you have set no onError, the message is printed to stderr as aether: ....

Close codes you will see

The code in onClose is the peer's if it sent one. The table lists every code the SDK produces or documents.

CodeWhoMeaning
1000eitherNormal close; the code of your own close().
1002clientA protocol error from the server, or a message the replica refused when closeOnMalformed is on.
1003clientThe server sent a text frame: the protocol is binary only.
1006clientNo close frame: the socket just went away, or idleTimeoutMs ran out ("idle timeout"). Also used with the reason "the server closed the connection".
1009clientA message larger than Options::maxMessageBytes (1 MiB by default).
4000serverYou were refused, with a readable reason: a contract mismatch (section 14), onJoin threw, or the rows the server fetches before you join did not load in time.
4001serverThe game kicked you (p.kick(reason)).
4290serverYou went on sending after the warning: too many messages (Options::rate) or too many of one type.
4291serverYour connection did not take what the server sent for Options::stalledSeconds (300 by default): "the connection did not take what the server sent for 300 s".

Codes 3000 to 4999 are the game's range; 4000 to 4001 and 4290 to 4291 are used by the SDK as above. Over GNS the code travels as GNS's end reason (the code minus 2000) and the reason as its debug string; the client puts them back for you.

When the connection drops

With options.connection.reconnect = true the connection retries by itself. When an attempt fails or an Open connection ends other than by your own close(), the next attempt is made after reconnectMinMs; every failure in a row multiplies the wait by reconnectFactor up to reconnectMaxMs; an attempt that opens resets it; reconnectJitter takes up to that fraction off each wait so that many clients do not return together. maxReconnectAttempts failures in a row make it give up (state Closed); 0 never gives up. While waiting, connection().reconnecting() is true and reconnectInMs() says how long is left.

When the new connection opens: onOpen runs, the replica is cleared, the welcome and layouts arrive again (the views stay described, so nothing changes for your handles), ready() turns false until the new welcome and your row, onReady runs again, and a prediction starts over (section 11). Until the new connection's rows arrive, the rows of the lost connection stay readable.

session.reconnect() is the manual one: it restarts the connection whatever state it is in (open, closing, lost), closes it first, waits for that inside poll(), then connects. Unlike the automatic path, the rows and me() of the old connection are cleared at once; sends made meanwhile are queued. It works after close() too.

Next: reading the world.

5. Reading the world: typed views

The server sends rows of its views; you read them as plain structs. session.view<Row>() gives a TypedView<Row>: a small handle (copy it freely) onto the rows of one view. The view's name is the struct's name, or the name you pass: the server's view<Hero>("heroes") pairs with session.view<Hero>("heroes"), and view<Hero>() with session.view<Hero>().

auto players = session.view<Walker>();            // the view the server called "Walker"
auto purses  = session.view<meadow::Purse>();      // my own purse only: the server made it ownerOnly

players.onEnter([&](ecs::Entity e, const Walker& w) { std::printf("%llu appeared at %.0f,%.0f\n", (unsigned long long)static_cast<std::uint64_t>(e), w.x, w.y); });
players.onUpdate([&](ecs::Entity e, const Walker& now, const Walker& before) { /* a row changed */ });
players.onLeave([&](ecs::Entity e, const Walker& last) { std::puts("someone left"); });

players.each([&](ecs::Entity e, const Walker& w) { draw(w.x, w.y); });          // every row, newest values
players.others([&](ecs::Entity e, const Walker& w) { draw(w.x, w.y); });        // the same without my own row
if (std::optional<Walker> mine = players.find(session.me())) { /* a copy of my row */ }

Notice:

  • Rows are matched by name and type. When the layout of the view arrives (or changes), every member of Row is matched to the server's field of the same name and type. A member the server does not send, or sends as another type, is one onError and the view stays empty (ready() false). Fields the server sends that your struct does not list are skipped. A String<N> member must have the server's exact width.
  • Row must be a flat plain struct: integers, float, double, bool, String<N>, ecs::Entity, a plain struct, a std::array or List of those. Anything else is a compile error with that list in it.
  • A wrong view name is reported. After the first tick message of a connection, a view you asked for by name that the server never described is reported once to onError: "the server has no view called 'X' (it has: ...), so session.view<Row>("X") stays empty".
  • Events run inside poll(), as each row is applied. A tick's rows may be applied in part when a callback runs: the SDK does not defer events to the end of the tick.
  • One function per event. onEnter, onUpdate and onLeave each hold one function; setting it again replaces it. Two handles on the same Row and name share them (they share one state).

The calls, exactly

CallWhat it gives
ready()The server has described the view and Row binds to it.
size(), has(e)The number of rows, and whether entity e is in the view. 0 / false until ready.
entities()A span of every entity in the view, dense, in no promised order. Empty until ready.
find(e)std::optional<Row>: a copy of the newest row, or empty if e is not in the view. The copy is yours; it does not change at the next poll().
before(e)std::optional<Row>: a copy of the row the server sent before the newest (the same row if only one has arrived).
each(fn)fn(Entity, const Row& now, const Row& before) or fn(Entity, const Row& now) for every row. The form is chosen by what fn accepts.
others(fn)The same as each, without the entity of session.me().
alpha(e), timing(e), snapped(e)Section 6 and 7.
subscribe(e), ignore(e, ms)Section 5, "Explicit views and ignoring".
Trap: the header comment says find returns a pointer. The comment at the top of TypedView.h shows const Player* me = players.find(...) "valid until the next poll()". The code returns std::optional<Row>, a copy. This page follows the code.

What now and before mean

now is the newest row the server sent for that entity; before is the one it sent before it, or the same row if only one has arrived. They are kept per entity: a row the server did not resend (nothing changed) keeps its pair. A second update inside one tick replaces now and keeps before.

The before that onUpdate receives is the replica's own: the row as it was when the previous distinct tick began (equal to now for a row that entered in this tick). It can differ from the per-entity before of each for a view the server sends every k-th tick.

Explicit views and ignoring

On a view the server made Subscribe::Explicit, a row that arrives is only an offer: the replica stores it, and your game answers with view.subscribe(e) (send me updates) or view.ignore(e, ms) (nothing about this entity for ms milliseconds; the row is removed at once). The server resends the Full of an unanswered entity on every send. The server cuts ms to its maxIgnoreMs (600000 by default). Both do nothing for a view that has not been described. On the default Auto view, subscribe is accepted and changes nothing. See Network: interest for the server side.

Next: drawing other players smoothly.

6. Drawing other players: before, now, alpha

The server sends a row only when something changed, and no more often than the view's send interval. If you draw each row the moment it arrives, other players jump from update to update. Drawing smoothly is rendering, not netcode: the SDK gives you the two rows and the fraction, and you write one line.

examples/meadow/client.cpp
static double lerp(double a, double b, double t) { return a + (b - a) * t; }

players.others([&](ecs::Entity e, const Walker& now, const Walker& before) {
    const double a = players.alpha(e);                     // 0..1, per entity
    draw(lerp(before.x, now.x, a), lerp(before.y, now.y, a));
});

Notice:

  • The SDK never interpolates, extrapolates or blends. There is no playhead, no jitter buffer and no speed adjustment. alpha(e) is the time since now arrived divided by the view's send interval, clamped to 0 to 1. It stays 1 when the updates stop, and is 1 for an unknown entity. An angle that wraps at plus or minus pi is yours to handle in your lerp.
  • You draw one send interval behind the newest data. The draw runs from before to now over the interval; it is the price of smoothness, and it is how the SDK is built.
  • The interval is the server's every(k). A view sent every third tick takes three ticks to climb from 0 to 1. The server sends every with the view's layout, so the client does not guess it. The tick length is 1000 / tickRate() ms; if the tick rate is not known yet the client uses 20.

Your own timing: timing(e)

If you want to extrapolate or blend on your own schedule, timing(e) returns the numbers behind alpha, or empty for an unknown entity.

Timing fieldMeaning
beforeTickThe server tick of the row before.
nowTickThe server tick of the row now.
intervalTicksThe view's send interval in ticks: the server's every(k); 1 for a view sent every tick.
msPerTick1000 / tickRate() (50 if the rate is unknown).
msSinceNowMilliseconds since now arrived here (steady clock).
snappednow arrived as a snap: do not blend from before (section 7).
snapTickThe server tick of the entity's last snap; 0 if none seen. "snapTick larger than the stamp you last looked at" means "it snapped since".
Trap: do not use the tick stamp as a clock. A client with nothing new is sent no tick message for about a second, so session.tick().stamp skips ticks and tick().count counts messages, not ticks. Use serverTime() (section 13).

Next: the one exception to blending.

7. Snaps: when not to blend

A portal, a respawn, a teleport: the entity's row changed by a jump, and blending from before would drag it across the map. The server marks such a change with snap(e) (or snap(e, row), which is set plus snap). Clients that already have the entity are sent the whole row marked as a snap; a client that does not have it yet is sent a plain Full, since a first row has no motion to blend.

players.others([&](ecs::Entity e, const Walker& now, const Walker& before) {
    if (players.snapped(e)) draw(now.x, now.y);                      // draw it where it is
    else draw(lerp(before.x, now.x, players.alpha(e)), lerp(before.y, now.y, players.alpha(e)));
});

snapped(e) is true when the update that brought now was marked a snap. before is still the true previous row; the SDK does not rewrite it. The flag stays true until an update of that entity arrives in a later poll() than the one that applied the snap, so a snap and the next change that arrive together are both seen as a snap by a game that looks once per poll. It is false for an unknown entity.

A snap arrives in onUpdate like any update (the replica reports it as RowEvent::Snap); check snapped(e) inside it. At the replica level, a snap of a row the client does not have is an Enter.

Your own row. A snap of your own predicted row is just a difference the server reports: it shows up as a correction (section 11) with was and is far apart. Correction has no flag for it. Ask the view with players.snapped(session.me()), or use the distance. me.reset() forgets the history if you want a fresh start after a snap.

Next: sending things to the server.

8. Sending messages and receiving them

A game message is a plain struct. session.send(Chat{...}) sends it; session.on<Said>(fn) receives one. The id on the wire is not yours to choose: the server hands out ids in registration order and sends the table to every client right after the welcome, and the client finds a message by its struct's unqualified name.

session.on<meadow::Said>([](const meadow::Said& s) {
    std::printf("%s: %s\n", s.who.str().c_str(), s.text.str().c_str());
});

if (session.ready()) session.send(meadow::Chat{String<80>("hello")});

Notice:

  • Traffic is one way each way. A handler on the server returns nothing. The server answers, when it chooses, with a message of its own (session.on<Result>) or with the rows you read. One answer per send is not promised.
  • Sends made early are queued. Before the connection is open and the server's id table has arrived (or while it is closing), the message is queued and goes out in order then. The queue holds at most 256; the one that does not fit returns SendResult::Full and reports "send(): the queue of messages waiting for the connection is full (256). Call connect() / reconnect() and poll()" to onError.
  • A name the server does not know throws. Once the table is in, sending a struct the server has no handler for (or one the server only sends) throws std::logic_error ("the server has no handler for it"). session.handlesMessage("Chat") asks first; it is false until the table has arrived (idsReady()).
  • on<M> checks the size. A body of the wrong size is reported to onError, counted in malformed(), and the function is not called. Two message structs with the same unqualified name make on<M> throw std::logic_error naming both. A handler that throws is reported to onError.
  • Order against moves. A plain message is not ordered against the input stream (held inputs and moves). The server handles plain messages when it reads the client, before it applies the inputs of the same batch. A command whose order against movement matters belongs in the move stream (section 10).

SendResult

ValueMeaning
OkSent, or queued by the session.
FullNo room: the connection's outgoing queue is over maxQueueBytes (try after the next poll()), or the session's queue of 256 is full. Counted in sendsFailed().
TooLargeThe message alone is larger than maxQueueBytes; it never fits. Counted in sendsFailed().
NotOpenClient only: the connection is not open, or is closing. Connection::send returns it (it does not queue); Session::send queues instead.

The raw forms are sendRaw(type, body) (a type byte of 16 or more is yours) and sendNamed(name, body); send(message) is built from them. onMessage receives every message type that has no typed handler.

Next: your own player.

9. Predicting your own player

With the server's rows alone, your own player answers a key press one round trip late. Prediction removes the wait: you run the same movement rule on your own copy of the state at once, and the server's answer only confirms it, or corrects it.

The model, in one paragraph. The controls are a struct the game defines, the held input (Move in meadow). The client cuts one copy of it per input step, numbers it with the next sequence number, runs your step function on its own copy of the state, keeps the input and the state it produced in a small ring (the history), and sends the inputs in batches. The server queues the inputs and applies them one at a time with the same function. It writes the number of the last input it consumed into the header of every tick message (the ack). When a tick arrives the client drops history up to the ack, overwrites the part of its state that the server owns with what the server says, and if that differs from what it predicted for that ack, it replays every unacknowledged input on top. That is a correction.

examples/meadow/client.cpp
auto me = session.predict<Walker>();   // my own row of the view "Walker" is the server's state
me.apply<Move>(step);                   // the SAME step the server runs: step(Walker&, const Move&, float dt)
session.connect();

while (running) {
    session.poll(5);                     // receive, reconcile, cut input steps, send
    me.input(Move{axisX, axisY});        // every frame: the controls as they are now
    const double a = me.alpha();         // how far into the current input step, 0..1
    draw(lerp(me.before().x, me.now().x, a), lerp(me.before().y, me.now().y, a));
}

Notice:

  • predict<Walker>() reads the server's state from view<Walker>().find(session.me()). With a view named differently, session.predict<Walker>("players"). The view must exist on the server with that name.
  • The step function is the shared function from Shared.h. Because both sides run the same code, a correct prediction costs one comparison and no replay.
  • me.input(...) is called every frame, but the SDK cuts steps at the server's input rate, learned from the welcome. Your frame rate and the input rate are independent.
  • me.now() and me.before() are plain values of the type Walker; alpha() is the fraction of the current input step that has passed. Read it after session.poll(). The SDK does not blend them: lerp(before, now, alpha) is your line.
  • You can also write client::Prediction<Walker> me(session, {.sendRate = 20});. A Prediction is movable, not copyable. There is one prediction per session: a second session.predict throws std::logic_error ("a session has one input stream, so one Prediction... Predict several rows of the player at once with session.predict<A, B>()").

What the SDK does inside poll()

A prediction is a poll hook: it runs inside session.poll(), after the messages of that poll were applied. In order:

  1. Wait until active. It is not active until the welcome has arrived (the input rate), the id table has arrived, and serverState() has said true once. Then the state is what the server says, and sequence numbering starts at 1 (the server counts from 1 per connection). A reconnect starts again.
  2. Reconcile if a tick message arrived in this poll (section 11).
  3. Cut. It advances a time accumulator by the time since the previous poll (clamped to 0.25 s). For every whole input step (1 / inputRate() seconds) in it, at most maxCatchUp (5) per poll (time beyond that is dropped), it takes the newest input(), runs your step function at once with dt = 1 / inputRate(), and stores {sequence, input bytes, state after} in the history ring. A step is skipped if no input() has been given yet, if no apply is registered, or if idle says the input does nothing.
  4. Send. At sendRate batches a second, every entry not yet sent goes in one message (type 8) per 32 entries.

The rates, each separate

WhatWhere it is setDefault
Server tickserver::Options::tickRate20 a second
Input step (cuts a second)The server's InputPolicy::rate0, meaning the tick rate
Your sampleHow often your game calls me.input()your choice
Client sendPredictOptions::sendRate (batches a second)0, meaning the server's tick rate; never above the input rate
Most cuts per pollPredictOptions::maxCatchUp5
HistoryPredictOptions::history128 (at least 4 is used)
Entries per batch messagefixed32

None of the rates is hard-coded on the client: the welcome announces the tick rate and the input rate, so the client and the server always agree. stepSeconds() is 1 / inputRate() (0 before the welcome).

Trap: sendRate above the input rate is clamped silently. The batch rate is min(sendRate or tickRate, inputRate); no error is raised.

The held input stays held

me.input(x) only stores the newest value; it never clears it. Every input step uses the newest value until you call input() again. To release the controls, send a neutral value (Move{0, 0}), or tell the prediction that a neutral value does nothing with idle:

me.idle<Move>([](const Move& m) { return m.dx == 0 && m.dy == 0; });

When idle returns true for the held value, no step is cut and nothing is sent for it. The server then has nothing to apply for you (see Starved in Server), and the ack does not advance. Use it for a game where "no key held" means no action at all.

The wire format of an input batch

Type 8, client to server, little endian: [first sequence u32][count u8], then count entries of [kind u8][packed input]. Sequence numbers in a message are consecutive (entry j has first + j); held inputs and moves share one counter per connection. Kind 0 is the held input, kinds 1 to 255 are moves. A kind whose struct contains a List is sent [kind][length u8][bytes]. The packed form is the members in declaration order with no padding; String<N> is N bytes.

A held input or a move is at most 255 bytes packed (a List counts at its full size); a longer struct is a compile error. Sequence comparisons use signed 32-bit differences, so a wrap-around is handled.

There is no resend. The transport is reliable and ordered, so the client never sends an input twice. PredictOptions has exactly three fields: sendRate, maxCatchUp, history.

Next: one-shot moves.

10. Moves, messages and the refused move

Not everything the player does is "held". A dash, a jump, a use-item is a one-shot: do it once, now. Aether calls it a move. A move is numbered in the same stream as the held inputs, so the server applies it in order with the movement around it, and the client can predict it and replay it on a correction.

Extend meadow with a dash that is refused at the edge of the field. The rule is shared, so both sides refuse the same way:

examples/meadow/Shared.h
struct Dash { float dx, dy; };            // a one-shot move

inline void dash(Walker& w, const Dash& d, float) {
    const double nx = w.x + d.dx * 40, ny = w.y + d.dy * 40;
    if (std::abs(nx) > 500 || std::abs(ny) > 500) return;      // refused: change nothing
    w.x = nx;
    w.y = ny;
}
examples/meadow/World.h (onStart)
on<Dash>(dash);                          // a move AND a message handler: the same function
examples/meadow/client.cpp
me.on<Dash>(dash);                       // predicted here: how a Dash changes my state
// ...
if (spacePressed) me.act(Dash{axisX, axisY});

Notice:

  • me.act(x) returns void. It numbers the move at once (the next sequence number), runs me.on<Dash>(fn) on your state with dt = 0, and the move goes out with the next batch. There is no answer to wait for: what the server decides comes back as rows (a correction replays your move) or as a message.
  • A move with no me.on<Dash>() is not predicted: me.act(Dash{..}) only sends it.
  • The server's on<Dash>(fn) registers both the message handler and, if the struct packs to at most 255 bytes, the move handler. A struct larger than 255 bytes can only be sent as a message; me.act of it throws std::logic_error ("... is only a message on the server (...): send it with session.send(X{..}), not me.act").
  • A move made before the prediction is active waits and goes out when it is. If the server's table does not know the name, the error goes to session.onError and the move is dropped; once the table is in, me.act of an unknown name throws std::logic_error ("the move X was not sent: the server has no handler for it (no on<X>() there)").
Trap: a full ring drops the move silently. If the history ring is full (the server has stopped acknowledging), act numbers nothing and sends nothing, and onStall is the only signal. Do not promise delivery of a move.

The refused move

Handlers return nothing, so a server cannot say "no" with a return value. A refusal travels the way every other result does: as state.

  1. The client predicts the move with me.on<Dash>(dash); the refusal rule (the edge of the field) is inside the shared function.
  2. The server runs the same function. If the rule refuses, the function changes nothing.
  3. If both sides agree on the refusal (they run the same function on the same state), there is no correction at all. If they disagree, the next tick's row differs from what the client predicted for that ack, a correction replays your unacknowledged inputs without the effect, and correction().serial rises.
  4. To tell the player why, the server sends a message (send(p, Result{..})) and the client reads it with session.on<Result>(fn). me.onAck(fn) runs when the server acknowledges input N, which is the moment to cancel a predicted telegraph.

Held input, move, message: which to use

Held inputMoveMessage
Client callme.input(x) every frameme.act(x)session.send(x)
Server registrationinputs().apply<X>(step)on<X>(fn)on<X>(fn)
Numbered in the shared sequenceyes, cut per stepyes, taken at onceno
Predictedme.apply<X>(step)me.on<X>(fn), optionalno
dt seen by the function1 / inputRate()0n/a
Replayed on a correctionyesyes, if registered with me.onno
Ordering against held inputsin sequencein sequencenone promised
Largest255 bytes packed255 bytes packed4096 bytes, client to server
Limitsserver queue and per-tick policymaxActions per tick; the ringthe connection's rate limit, and limit<X>

Messages are counted by the connection's rate limiter (Network: the rate limiter); the input message is not, because inputs have their own budget on the server. Next: the corrections themselves.

11. Corrections and replay

Every time a tick message is applied, the prediction asks one question: does what the server says about me equal what I had predicted for the input it acknowledged? Here is exactly what happens, because "the prediction was right" is the common case and a correction is the exception.

  1. Ack. The tick header carries N, the last input sequence the server consumed for you. If N is newer than the last ack (an ack beyond the last numbered input is clamped), history entries up to N are dropped, the state the client had after N becomes acked, the stall flag clears, and onAck(N) runs.
  2. Compare. serverState(base) overwrites the part of a copy of acked that the server owns; what it leaves alone keeps your own value as of N. If serverState returns false (the row is not there yet) nothing more happens. If base equals acked field by field (padding does not count; floats compare bytewise), the prediction was right: stop. No replay, no correction.
  3. Replay. Otherwise cur = prev = base, and every history entry after N is run again (held inputs with dt = stepSeconds(), moves with dt = 0), rewriting each saved state. stats().replays goes up, correction() is filled in, and onCorrection(before, after) runs.

The comparison happens on every tick message, also when the ack did not move. So a server-side change of your row that did not come from your input (a teleport, a knockback, a cooldown reset) is also detected as a correction.

The Correction value

Member of Correction<State>Meaning
serial0 = never; +1 per correction. The game compares it to the one it has seen.
sequenceThe input sequence the server had applied (the ack).
wasnow() just before the correction.
isnow() just after: the server's state with the unacknowledged inputs replayed.
atA steady_clock time point of the correction.
age()Seconds since at; 0 if serial is 0.

was minus is is the error to hide. The SDK does not ease it: it exposes the value and you decide.

double errX = 0, errY = 0;
std::uint32_t seen = 0;

void drawMe(client::Prediction<Walker>& me, double dt) {
    const double a = me.alpha();
    double x = lerp(me.before().x, me.now().x, a);
    double y = lerp(me.before().y, me.now().y, a);

    const auto& c = me.correction();
    if (c.serial != seen) {                               // a new correction
        seen = c.serial;
        errX = c.was.x - c.is.x;
        errY = c.was.y - c.is.y;
        if (std::hypot(errX, errY) > 128) errX = errY = 0;   // too far to ease: snap
    }
    errX *= std::exp(-dt / 0.08);                         // ease the error away
    errY *= std::exp(-dt / 0.08);
    draw(x + errX, y + errY);
}

The constants 0.08 s and 128 units are yours. They are what a game chose, not something the SDK provides.

Trap: side effects do not belong in the shared functions. Your step function runs again on every replay, 2 to 12 times a frame in the worst case. A sound, a particle, a log line or a counter in it would fire again and again. Raise them from now() in your game code instead.
Trap: the state must be small and trivially copyable. State is copied into every history entry; a non-trivially-copyable type is a static_assert failure. A large physics world would need save and restore hooks, which the SDK does not have.

What the server may do that you did not predict: when no held input is queued and the client has sent at least one before, the server's Starved policy may apply a repeat or neutral step; those steps are never numbered by the client, never move the ack, and the client's next comparison corrects the difference. A bounded queue that overflowed under Excess::Wait also drops the oldest held input without applying it; the client replays it, and the disagreement shows as a correction. Both are described in Server.

Next: more than one row, and watching the machinery.

12. Several rows, your own state, and watching it work

Several rows in one prediction

A player may be made of two rows: a public Hero and an owner-only Mine. session.predict<Hero, Mine>() predicts both together. The state is aether::Rows<Hero, Mine>, a trivially copyable aggregate; your step takes the rows by reference, and each Row& parameter is found by its type.

struct Hero { double x, y; float hp; };           // a public row
struct Mine { std::uint32_t gold; };             // an owner-only row

inline void stepBoth(Hero& h, Mine& m, const Move& in, float dt) { h.x += in.dx * dt; m.gold += (in.dx != 0 || in.dy != 0) ? 1 : 0; }

auto me = session.predict<Hero, Mine>();       // or ({"heroes", "mine"}) if the view names differ
me.apply<Move>(stepBoth);
// me.now<Mine>().gold, me.before<Hero>().x, or: const auto& [hero, mine] = me.now();

One view name per row, in order, if they differ from the structs' names: session.predict<Hero, Mine>({"heroes", "mine"}). serverState of the multi-row form returns false until all rows are present. The same row type twice, a non-plain struct, or a Row& parameter that is not one of the predicted rows is a compile error.

State that is not rows: serverState

The default is "my row of the view". If your state is something else (a simulation with a field the server never sends), say what the server owns:

struct CarSim { Walker car; float rearGrip; };       // rearGrip is never sent

client::Prediction<CarSim> me(session);
me.apply<Move>([](CarSim& s, const Move& m, float dt) { step(s.car, m, dt); });
me.serverState([&](CarSim& s) {
    auto row = players.find(session.me());
    if (!row) return false;                         // not known yet
    s.car = *row;                                   // leave rearGrip as the client had it at the acked input
    return true;
});

When the server says nothing about a field, it keeps your value as of the acknowledged input. If such a field drifts from the server's, you will be corrected a little each tick; the fix is to send it (an owner-only view).

Watching it

CallReturns
active()The prediction is running (welcome, id table, and a known server row).
sequence()The last input numbered.
acked()The last input the server said it consumed.
pending()Entries numbered and not acknowledged (the ring's count).
stepSeconds()1 / inputRate(); 0 before the welcome.
stats(){cut, acted, sent, replays, stalls}, cumulative: held steps cut, moves numbered, batch messages sent, corrections replayed, stalls entered.
resetStats()Zero the counters (before the part of a test you measure).
reset()Forget the history and start again from serverState(). Automatic on a reconnect; call it yourself after a snap you know about.
onStall(fn)The history ring is full: the server has stopped acknowledging. Nothing is cut while it is full. Runs once per stall; a later ack clears it.
onAck(fn(seq))A new ack arrived.
onCorrection(fn(before, after))A correction happened (same values as correction()).

Next: telling time.

13. The server clock

"The round ends in 20 seconds." If the server stores endsAt = time() + 20.0 on its game clock, the client shows endsAt - session.serverTime(). serverTime() is seconds on the server's game clock (the same scale as Game::time()): 0 until the first tick, never going backwards, and advancing between messages.

How it is estimated. On each tick message the client computes offset = nowMs - stamp * 1000 / tickRate and keeps the last 32 offsets. A tick message is only ever late, never early, so the smallest offset is the best estimate of the difference between the two clocks: jitter is filtered out and skipped ticks do not matter. serverTime() is then max(last answer, (nowMs - offset) / 1000). It needs the tick rate (the welcome); ticks are ignored while it is 0. It is reset on every new connection.

Accuracy. There is no latency compensation: serverTime() lags the true server time by about the one-way delay (tens of milliseconds), plus a frame. That is fine for a countdown, and wrong for lag compensation or anything below a tick. The client has no round trip of its own, so none is used. The minimum is taken over the last 32 tick messages; right after connecting, with fewer than 32 samples, it is the minimum of the ones that have arrived.

Store deadlines as absolute times on the server (endsAt = time() + 30.0); do not use tick().stamp as a clock, because it skips ticks when nothing changes. A game that restarts its server restarts time() from 0; persist time left, not an absolute time (see Saving).

The newest tick, and poll count

session.tick() returns Session::Tick{stamp, inputSequence, receivedMs, count}: the newest tick message's stamp (the server's tick number), the input sequence the server had applied, when it arrived (steady clock, ms), and the tick messages applied since the connection opened. A large tick that does not fit one message is split into several, each with the header, so count counts messages. session.pollCount() is how many times poll() has been called.

Next: the version check.

14. The contract: refusing a stale client

If the server is rebuilt from a changed .aether file and an old client connects, rows would mis-parse. The contract prevents it. The generated header has meadow::contract (the file name and a fingerprint of the whole file: every message and enum, every member, type and fixed id; a comment or the order of the messages does not change it). Give it to both sides.

// server: server::Game({.contract = meadow::contract})
client::Session session("ws://localhost:9000/?name=Ayla", {.contract = meadow::contract});
session.onClose([](std::uint16_t code, std::string_view why) { /* 4000 and a readable reason */ });

The client sends contract=<16 hex digits>&schema=<file name> in the connect query (the schema name is left out if it has a character a query cannot hold). The rule: both give one and they match, or neither gives one. The refusal is close code 4000 and a reason you can read in onClose:

  • "client and server were built from different versions of meadow.aether (rebuild the client from the same file)"
  • "this server requires the contract meadow.aether; the client sent none (build the client from the same file and give its Session the contract)"
  • "the client was built from meadow.aether but this server has no contract (give the Game `.contract = <namespace>::contract`)"
Reasons are cut at 123 bytes. A close reason is at most 123 bytes, so the longer refusals reach onClose shortened: running a client without a contract against a meadow server gave 4000: this server requires the contract meadow.aether; the client sent none (build the client from the same file and give its Ses. Match on the code and the beginning of the text.

Next: below the session.

15. GNS, and below the session

Using GameNetworkingSockets

The gns:// form needs one include and one library: #include <aether/client/GameSocket.h> and link aether_client_gns. Including the header is all the registration there is: without it a gns:// connection fails with a message that says so.

examples/client/client.cpp
#include <aether/client/Session.h>
#include <aether/client/GameSocket.h>   // lets "gns://host:27015/" work (link aether_client_gns)

client::Session session("gns://localhost:27015/?name=ann");   // everything else as with ws://

The server is an App listening with server::GameSocket{27015}. GNS has no URL: the query of the URL is sent as the hello, the first message of the connection ([type 9][query text]). name, contract and maxBytesPerSecond work as on WebSocket. The client initialises GNS once per process and never shuts it down, and never calls RunCallbacks(), so it can live in the same process as a looping server. It has no socket to wait on: Connection::fd() is -1, poll(timeoutMs) waits in steps of 1 ms, and queuedBytes() is 0 (GNS holds the queue). A host is an IP address or a name, resolved at each attempt. The server side is in Network: transports.

The replica: rows, field by field

The typed views are made on client::Replica, which keeps, per view, the rows of the entities you are subscribed to as raw bytes, with the layout the server described. You can use it directly (the example examples/client does). The server's tick message, applied by the replica:

  • Full stores the row (replacing one it has); onFull runs.
  • Snap is like a Full (the same body); the event is RowEvent::Snap when the row existed.
  • Delta writes the changed fields into the row it has; onDelta runs with the mask. If it has no row for the entity, it sends the server a don't know message (once per entity until a Full of it arrives) and ignores the Delta.
  • Unsubscribed removes the row; onUnsubscribed runs before the row goes. Ignored if there is no row.
  • After all the entries: onTick(stamp, inputSequence).

A malformed message (a wrong length, an unknown kind, a view that was not described) is not applied in part: apply and describe check the whole body first, change nothing, and throw std::invalid_argument. The session turns that into an onError and the malformed() counter. The replica also hides the server's crowd path: pieces of grid cells are applied so that the game sees only rows.

examples/client/client.cpp
session.replica().onTick([&](ecs::Stamp stamp, std::uint32_t) {
    const client::ReplicaView* v = session.replica().view("entities");
    if (!v) return;
    const auto x = v->type.field<double>("x"), y = v->type.field<double>("y");
    session.replica().each(v->id, [&](ecs::Entity e, ecs::ConstRow row) {
        std::printf("%llu %.1f %.1f\n", (unsigned long long)static_cast<std::uint64_t>(e), row.get(x), row.get(y));
    });
});

A row is valid until the next apply, describe or forget. The full list of members is in the reference.

The connection

session.connection() is a client::Connection: a minimal RFC 6455 client over a non-blocking POSIX socket, no thread, no lock, no dependency but poll(2) (Linux, macOS). You can use it alone for a bot or a test. It answers the server's type-1 ping by itself with {int64 t, uint16 interpMs}; the server measures the round trip when the echo arrives, so the client has no round trip of its own to expose. interpolationMs (or setInterpolationMs) is the interpolation delay you tell the server; it arrives as p.link().interpMs and the SDK uses it for nothing on the client.

Not in this library on purpose: TLS (terminate it in front of the server and connect to the proxy's plain port or use a tunnel), WebSocket extensions (permessage-deflate is not offered), text messages (a text frame from the server closes with 1003), and an asynchronous resolver.

The reference follows. Every public item of Session, TypedView, Prediction, Replica, Connection and client::Options is listed.

Reference

Every public member, grouped by class. Defaults and ranges are the ones in the headers; "throws" means a thrown exception, "reports" means a call to onError (or stderr when none is set). All of it is on the caller's thread; none of it is thread safe.

client::Session

explicit Session(SessionOptions options = {});
explicit Session(std::string_view url, SessionOptions overrides = {});
ParameterMeaning
optionsEverything the session needs. The contract and maxBytesPerSecond are appended to the connection's path as a query. Throws std::invalid_argument naming the field if connection is invalid (Options::validate).
urlws://host[:port][/path][?query] or gns://host:port[/path][?query]. Throws std::invalid_argument for anything else (wss:// included).
overridesThe options; its connection's host, port, path and transport are replaced by the URL's.

Not copyable. The destructor drops the socket, sending a close frame first if Open (best effort, no waiting).

Connection control

SignatureBehaviour
Connection& connection()
Replica& replica()
const Replica& replica() const
const SessionOptions& options() const
The parts of the session and the options it was built with (with the contract and maxBytesPerSecond already in the connection's path). They live as long as the session.
bool connect()Starts connecting. False if the attempt failed at once and no retry is scheduled (onError said why); true for a no-op while Connecting or Open.
int poll(int timeoutMs = 0)Waits up to timeoutMs (0: no wait; negative: until something happens, which includes the end of a backoff), does the I/O, applies messages, runs callbacks and poll hooks (the prediction), and fires onReady once when the session becomes ready. Returns the messages the connection delivered. A Closed connection returns 0 at once. Increments pollCount().
void close(std::uint16_t code = 1000, std::string_view reason = {})Starts the close handshake. code: 1000 or 3000 to 4999; reason: at most 123 bytes. No callback if still Connecting. No-op when Closed.
void reconnect()Restarts the connection whatever its state; clears rows, me(), the tick, the clock and the id table at once; ready() false until the new one is ready; sends meanwhile are queued. Works after close().
bool connected() constOpen and not closing.

Callbacks

SignatureBehaviour
void onOpen(std::function<void()>)After a connection opened and the replica was cleared.
void onClose(std::function<void(std::uint16_t code, std::string_view reason)>)An Open connection ended. Code table: section 4.
void onError(std::function<void(std::string_view what)>)Connection errors and malformed server messages; any reportError.
void onMessage(std::function<void(std::uint8_t type, std::span<const std::uint8_t> body)>)Every message type that is not the replica's, the welcome, the id table, a warning or a typed handler.
void onWarning(std::function<void(std::string_view text)>)The server dropped messages of this client for sending too many. The text is the server's, for example "too many messages: the limit is 30 messages a second (burst 60), 16384 bytes a second; what is over it is dropped" or "too many Chat messages: the limit is 2 per 1000 ms; what is over it is dropped".
void onReady(std::function<void()>)Once per connection, inside poll(), when ready() becomes true.

Welcome, tick and time

SignatureReturns
ecs::Entity me() constYour entity from the welcome; ecs::kNoEntity until it arrives, after a reconnect until the new one, and for a spectator.
int tickRate() const
int inputRate() const
The server's ticks a second and input steps a second; 0 until the welcome.
bool welcomed() constinputRate() > 0.
bool ready() constOpen, welcomed, and your row present in some view (or no entity).
Tick tick() const{ecs::Stamp stamp = 0; std::uint32_t inputSequence = 0; std::int64_t receivedMs = 0; std::uint64_t count = 0;}: the newest tick message's stamp, the input sequence it carried, when it arrived (steady clock ms; updated only when the stamp changes), and how many tick messages were applied since the connection opened.
std::uint64_t pollCount() constHow many times poll() has been called.
double serverTime() constSection 13.

Views and prediction

SignatureBehaviour
template <class Row> TypedView<Row> view(std::string_view name = {})name: the server's name for the view; empty means the struct's name. Never null; may be called before connect().
template <class Row> Prediction<Row> predict(PredictOptions options = {})
template <class Row> Prediction<Row> predict(std::string_view viewName, PredictOptions options = {})
My own row of the view of Row, predicted. One prediction per session: a second throws std::logic_error.
template <class A, class B, class... More> Prediction<Rows<A, B, More...>> predict(PredictOptions options = {})
the same with std::array<std::string_view, N> viewNames first
My row of each view together. me.now() is a Rows<A, B>. The same row type twice is a compile error.

Messages and ids

SignatureBehaviour
template <class M> SendResult send(const M& message)M must be a plain struct (public members, no constructors), else a static_assert. Sent under the id the server's table gives the struct's name; queued (at most 256) until the connection is open and the table has arrived; throws std::logic_error for a name the server does not know once the table is in.
SendResult sendRaw(std::uint8_t type, std::span<const std::uint8_t> body)A message by type id. Queued while not open. Full/TooLarge are counted in sendsFailed(). The connection throws std::invalid_argument for type 0 or 1.
SendResult sendNamed(std::string_view name, std::span<const std::uint8_t> body)What send is made of.
template <class M> void on(std::function<void(const M&)> fn)
template <class M, class Fn> void on(Fn&& fn)
Handles messages of M. A wrong-size body is reported and counted in malformed(). Two structs of one unqualified name throw std::logic_error. A type below 16 for a macro message throws std::invalid_argument.
bool idsReady() constThe server's table of ids has arrived on this connection (false after a connection opens, until it comes).
bool handlesMessage(std::string_view name) constThe server has a handler for the message name; false before the table.
std::optional<std::uint8_t> actionId(std::string_view name) constThe wire id of the server's move handler for name, or empty.

Replica pass-throughs and counters

SignatureBehaviour
void subscribe(std::uint16_t view, ecs::Entity entity)Replica::subscribe: for Explicit views. Nothing for a view that has not been described.
void ignore(std::uint16_t view, ecs::Entity entity, std::uint32_t ms)Nothing about entity for ms ms (the server cuts it to its maxIgnoreMs). The row is removed at once.
void dontKnow(std::uint16_t view, ecs::Entity entity)Sends the message the replica sends by itself for a Delta without a row, for a game that manages its rows itself.
std::size_t malformed() constMessages the replica or a typed handler refused.
std::size_t sendsFailed() constSends the connection refused (subscribe, ignore, don't know, send). Not retried.
std::size_t layouts() constLayout messages applied since construction.

Advanced (what Prediction and TypedView are made of)

SignatureBehaviour
int addPollHook(std::function<void()>), void removePollHook(int id)A hook runs inside poll() after the messages of that poll were applied. The id is for the removal.
void addViewSink(std::type_index row, std::shared_ptr<ViewSink> sink), std::shared_ptr<ViewSink> findViewSink(std::type_index, const std::string& name) constRegisters the receiver of the row events of one view (ViewSink::viewName(), rowEvent(kind, view, entity, now, before)); what a TypedView does.
void reportError(const std::string&)To onError, or stderr if none.
void setInputStream(const void* owner), const void* inputStream() constOne input stream per session: the prediction is it. A second owner throws std::logic_error.
void noteSendFailed(SendResult), std::uint64_t generation() constCount and report a failed send; generation() grows on every open (a prediction starts again).

See also: sections 1 to 4, 8, 13, 14.

SessionOptions and ReplicaOptions

struct SessionOptions {
    Options connection;
    ReplicaOptions replica;
    bool clearOnOpen = true;
    bool closeOnMalformed = false;
    Contract contract = {};
    std::uint32_t maxBytesPerSecond = 0;
};
struct ReplicaOptions {
    std::uint8_t tickType = 2, subscribeType = 3, ignoreType = 4, dontKnowType = 5, layoutType = 6;
    std::size_t reserve = 1024;   // rows to allocate per view up front
};

Field meanings are in section 2. The five message types must be the server's InterestPolicy types. reserve is rows per view allocated up front.

client::Options

static Options Options::fromUrl(std::string_view url);   // throws std::invalid_argument
void validate() const;                                     // throws std::invalid_argument naming the field
FieldTypeDefaultValidMeaning
hoststd::stringthe IPv4 loopback addressnot emptyAn IPv4 or IPv6 address or a name (a name is resolved with getaddrinfo, which can block).
portstd::uint16_t90001..65535Server port.
pathstd::string"/"starts with /, no spaces or line breaksWhat follows the host, with the query ("/world?token=abc").
headersstd::vector<std::string>empty"Name: value" each, no line breaksExtra request headers (Origin, Authorization).
transportTransportWebSocketWebSocket, GameSocketSet by fromUrl for gns://. A GameSocket needs aether/client/GameSocket.h included, else the connection fails with a message that says so.
reconnectboolfalseReconnect after a failed attempt or a lost connection.
reconnectMinMsint250at least 1The first wait.
reconnectMaxMsint8000at least reconnectMinMsThe longest wait.
reconnectFactordouble2.0at least 1The wait grows by this per failure in a row.
reconnectJitterdouble0.20..1Each wait is shortened by a random fraction of up to this.
maxReconnectAttemptsint0not negativeFailures in a row after which it gives up (state Closed); 0 = never.
answerPingsbooltrueReply to the server's type-1 ping with the echo. Off: the server never measures your round trip.
answerWebSocketPingsbooltrueReply to a WebSocket ping frame with a pong.
deliverPingsboolfalseAlso pass the type-1 ping to onMessage.
interpolationMsstd::uint16_t0The interpolation delay carried in the echo (arrives as Link::interpMs). Also setInterpolationMs().
maxMessageBytesstd::size_t1048576at least 1Largest message accepted from the server (type byte included); a larger one closes with 1009.
maxQueueBytesstd::size_t1048576at least 1Bytes of frames queued for the socket. Past it send returns Full; a message alone larger returns TooLarge.
connectTimeoutMsint5000at least 1TCP connect plus upgrade handshake.
closeTimeoutMsint1000not negativeAfter close(), how long to wait for the server's close frame; 0 = do not wait.
idleTimeoutMsint0not negativeClose with 1006 ("idle timeout") if nothing at all arrives for this long; 0 = never. (The server pings every pingIntervalMs, 1000 by default.)
tcpNoDelaybooltrueDisable Nagle on the socket.
readChunkBytesstd::size_t65536at least 512Bytes read per recv.
maxReadsPerPollint16at least 1recv calls per poll(); the rest is read by the next.

Example: auto o = client::Options::fromUrl("ws://localhost:9000/"); o.reconnect = true; o.maxReconnectAttempts = 10;

The enums: client::State { Connecting, Open, Closed }, client::Transport { WebSocket, GameSocket }, client::kPingType = 1.

client::Connection

SignatureBehaviour
explicit Connection(Options options = {})Calls options.validate().
const Options& options() constThe options.
bool connect(), int poll(int timeoutMs = 0), void close(std::uint16_t code = 1000, std::string_view reason = {})As for the session. close() cancels reconnecting.
SendResult send(std::uint8_t type, std::span<const std::uint8_t> body)Queues one frame. NotOpen if not Open or closing (it does not queue). Throws std::invalid_argument ("message types 0 and 1 are reserved") for type 0 or 1.
template <class Write> SendResult send(std::uint8_t type, std::size_t size, Write&& write)Zero copy: write(std::span<std::uint8_t>) encodes size bytes into the queued frame, and is not called unless the result is Ok. If it throws, nothing is queued. It must not call send.
State state() const, bool closing() const, bool reconnecting() const, int reconnectInMs() const, int failures() constState; close handshake in progress; waiting out a backoff; the time left to the next attempt (0 if not reconnecting); failed attempts and lost connections in a row since the last open.
const std::string& lastError() const, std::uint16_t lastCloseCode() constThe last onError text; the code of the last onClose (0 before the first).
std::size_t queuedBytes() const, int fd() constFrames waiting for the socket; the socket for a loop that waits itself (poll(2) it for POLLIN, and POLLOUT while queuedBytes() > 0 or Connecting, then call poll(0)); -1 when there is none (Closed, backing off, or GNS).
const Stats& stats() const{messagesIn, messagesOut, bytesIn, bytesOut, pings, opens}, all std::uint64_t, since construction. messages* exclude the pings answered here; bytes* are socket bytes; pings counts type-1 pings answered (or seen if answerPings is off).
std::int64_t lastPingStamp() const, void setInterpolationMs(std::uint16_t)The t of the last server ping (0 if none); the interpolation delay for the echo.
void onOpen/onMessage/onClose/onError(...)The same callbacks as the session's. The session installs its own; use these only on a connection you made yourself.

client::TypedView<Row>

Construct with session.view<Row>(name) or TypedView<Row>(Session&, std::string_view viewName = {}). Copyable; copies share state.

SignatureBehaviour
bool ready() constThe view is described and Row binds.
std::size_t size() const, bool has(ecs::Entity) constRow count, presence; 0 / false until ready.
std::optional<Row> find(ecs::Entity) constA copy of the newest row; empty if absent.
std::optional<Row> before(ecs::Entity) constA copy of the row before it (the same if only one arrived); empty if absent.
std::span<const ecs::Entity> entities() constEvery entity, dense, in no promised order. Empty until ready.
template <class Fn> void each(Fn&&) constfn(Entity, const Row& now, const Row& before) or fn(Entity, const Row& now); rows in storage order; before == now if only one row arrived. Does nothing until ready.
template <class Fn> void others(Fn&&) constThe same, without session.me().
double alpha(ecs::Entity) constTime since now arrived over intervalTicks * msPerTick, clamped 0..1; 1 if unknown or not ready.
std::optional<Timing> timing(ecs::Entity) constSection 6; empty if unknown or not ready.
bool snapped(ecs::Entity) constSection 7; false if unknown or not ready.
void onEnter(std::function<void(ecs::Entity, const Row& now)>)
void onUpdate(std::function<void(ecs::Entity, const Row& now, const Row& before)>)
void onLeave(std::function<void(ecs::Entity, const Row& last)>)
One function each; setting again replaces. Enter: the first row. Update: a Full over a row, a Delta, or a snap. Leave: an Unsubscribed, an ignore, a forget, a clear (reconnect), or a layout that replaced the view; last is the row it had.
void ignore(ecs::Entity, std::uint32_t ms), void subscribe(ecs::Entity)As the session's, for this view; nothing if not ready.
auto players = session.view<Walker>();
players.others([&](ecs::Entity e, const Walker& now, const Walker& before) {
    if (players.snapped(e)) draw(now.x, now.y);
    else draw(lerp(before.x, now.x, players.alpha(e)), lerp(before.y, now.y, players.alpha(e)));
});

Also: client::Timing {ecs::Stamp beforeTick = 0, nowTick = 0; int intervalTicks = 1; double msPerTick = 50, msSinceNow = 0; bool snapped = false; ecs::Stamp snapTick = 0;}. See also: sections 5 to 7.

client::Prediction<State>

explicit Prediction(Session& session, PredictOptions options = {});   // or session.predict<Row>(...)
struct PredictOptions { int sendRate = 0; int maxCatchUp = 5; int history = 128; };
PredictOptions fieldDefaultMeaning
sendRate0Batches a second; 0 = the server's tick rate; above the input rate, the input rate is used (silently).
maxCatchUp5The most input steps one poll() may run; the time beyond that is dropped.
history128Inputs and states kept (the ring); max(history, 4) is used. A full ring stalls.

State must be trivially copyable (a static_assert). The class is movable and not copyable or move-assignable. The destructor removes the poll hook and releases the session's input stream.

Set up once

SignatureBehaviour
template <class Input, class Fn> Prediction& apply(Fn&& fn)fn(State&, const Input&, float dt): the held input. One per game: a second held-input type throws std::logic_error ("...are both the held input (kind 0), and a game has one. If X is a move, register it with on<X>(fn)"). For a Rows state, fn(Row&..., const Input&[, float]). A static_assert fires if Input is an AETHER_ACTION. The struct packs to at most 255 bytes.
template <class Action, class Fn> Prediction& on(Fn&& fn)fn(State&, const Action&, float dt) with dt = 0: how a move changes the state. Optional. Two action structs of one unqualified name throw std::logic_error; more than 255 action structs throw too.
Prediction& serverState(std::function<bool(State&)>)Write the server's part of the state; false = not known yet. predict<Row>() installs "my row of the view".
template <class Input> Prediction& idle(std::function<bool(const Input&)>)True: this held input does nothing; no step is cut and nothing is sent.
Prediction& onStall(std::function<void()>)
Prediction& onAck(std::function<void(std::uint32_t)>)
Prediction& onCorrection(std::function<void(const State& before, const State& after)>)
Section 12.

Every frame, and reading

SignatureBehaviour
template <class Input> void input(const Input& controls)The held input as it is now; the newest value is what the next step uses. Input is a plain struct, not an action.
template <class Action> void act(const Action& action)A one-shot move. Section 10. Throws std::logic_error for a message-only struct or an unknown name; silently lost if the ring is full.
const State& now() const, const State& before() constThe newest input step, and the step before it. For several rows: now<R>() / before<R>() give one row.
double alpha() constHow far into the current input step, 0..1; 0 when not active. Read it after session.poll().
const Correction<State>& correction() constThe last correction (serial 0 = never).
bool active() const, std::uint32_t sequence() const, std::uint32_t acked() const, int pending() const, float stepSeconds() constSection 12.
const Stats& stats() const, void resetStats(), void reset()Counters {cut, acted, sent, replays, stalls}; zero them; forget history.
auto me = session.predict<Walker>({.sendRate = 20});
me.apply<Move>(step).onCorrection([](const Walker& was, const Walker& is) { /* ease */ });

See also: sections 9 to 12.

client::Replica

SignatureBehaviour
explicit Replica(ReplicaOptions options = {}), const ReplicaOptions& options() constNot copyable.
void setSender(std::function<void(std::uint8_t type, std::span<const std::uint8_t> body)>)Where subscribe, ignore and don't know messages go. Without it they are dropped.
const ReplicaView& describe(std::span<const std::uint8_t> layout)A layout from the server. Throws std::invalid_argument if malformed. The same layout again is a no-op; another layout replaces the view and drops its rows.
bool apply(std::uint8_t type, std::span<const std::uint8_t> body)False if type is neither the layout type nor the tick type. Throws std::invalid_argument if the body is malformed or names a view that was not described; nothing is applied then.
ecs::Stamp stamp() const, std::uint32_t inputSequence() constThe header of the last tick message; 0 before the first.
const ReplicaView* view(std::uint16_t id) const, view(std::string_view name) const, std::size_t views() constA view or nullptr; the number of views.
ecs::ConstRow row(std::uint16_t view, ecs::Entity) const, bool has(...), std::size_t size(std::uint16_t view) const, std::span<const ecs::Entity> entities(std::uint16_t view) constA false ConstRow if the view or row is not there. A row is valid until the next apply, describe or forget.
each(view, fn), each2(view, fn), ecs::ConstRow before(view, e) constfn(Entity, ConstRow) / fn(Entity, ConstRow now, ConstRow before) in storage order. before is the row as it was when the previous distinct stamp began.
void setObserver(ReplicaObserver)One observer (the session's): row(RowEvent, const ReplicaView&, Entity, ConstRow now, ConstRow before) and tick(Stamp, std::uint32_t inputSequence), in addition to the callbacks below.
void subscribe(view, e), void ignore(view, e, std::uint32_t ms)Through the sender. Nothing for an undescribed view. ignore removes the row at once (onUnsubscribed runs); the server's later Unsubscribed is ignored.
void forget(view, e)Drops a row without telling the server. No callback. No-op if absent.
void clear()Drops every row of every view; the views stay described; stamp() and inputSequence() are kept.
onFull(fn(const ReplicaView&, Entity, ConstRow)), onDelta(fn(const ReplicaView&, Entity, ConstRow, std::span<const std::uint8_t> mask)), onUnsubscribed(fn(...ConstRow)), onTick(fn(Stamp, std::uint32_t))Optional. mask: bit i set means deltaFields[i] was written. A callback may call forget, subscribe, ignore, clear; it must not call describe.
std::size_t dontKnowSent() const, std::size_t deltasIgnored() constCounters since construction: don't-know messages sent; Deltas for an entity without a row.

ReplicaView: id (uint16), name, explicitSubscribe, type (ecs::Type: type.field<T>(name) gives a field handle with offset and width), deltaFields (in mask order), serial (unique per describe() that made the view; a changed layout is a new serial), every (the server's every(k), default 1). RowEvent { Enter, Update, Leave, Snap }.

client::ServerClock

SignatureBehaviour
void onTick(std::int64_t stamp, int tickRate, double nowMs)A tick message with this stamp arrived at nowMs (any steady clock, milliseconds). Ignored while tickRate <= 0.
double at(double nowMs)Seconds on the server's game clock; 0 until the first tick; never goes backwards.
void reset()Forget the samples.

See also: Server for the registrations these calls pair with, Network for the transports, Testing for running a server and clients in one test.