simulateNetwork() function

Available since @irtio/client 5.0BrowsersNode

The simulateNetwork() function returns a dial for connect() that delays and drops messages as a slow network would, for trying a game under lag, jitter and loss during development. It’s exported by @irtio/client/dev.

Syntax

simulateNetwork(conditions)
simulateNetwork(conditions, options)

Parameters

conditions

An object with these properties, each applying each way between the client and the router:

rttMs
A number: the round trip to add, in milliseconds, half of it each way. 0 or more.
jitterMs Optional
A number: each one-way delay varies by up to this many milliseconds either side of rttMs / 2, never below zero. Defaults to 0.
loss Optional
A number from 0 to 1: the fraction of unreliable messages dropped each way. Reliable messages are only delayed. Defaults to 0.
options Optional

An object with any of these properties:

dial
A dial to wrap. Defaults to the one connect() uses, WebTransport and then WebSocket.
allowRemote
A boolean. If true, the dial runs against rooms on hosts other than localhost, a subdomain of it, 127.0.0.1 or ::1, such as a staging project. Defaults to false.
clock
The timers to delay with, for tests.
random
A function returning a number from 0 up to but not including 1, for jitter and loss, for tests. Defaults to Math.random.

Return value

A dial: a function to pass as the dial of a DevConnectInit, the init object with development hooks that connect() and new RoomClient() take.

Exceptions

RangeError
Thrown if rttMs or jitterMs is below 0 or not a number, or if loss isn’t from 0 to 1.

Against a room that isn’t local, without allowRemote, connect() rejects with an IrtError named NetworkError, of code 0, saying so.

Description

Reliable messages are delayed and stay in order. Unreliable messages, inputs and pings are delayed too, and can also be dropped and overtake each other. The dial delays the connection’s close by the same one-way delay.

@irtio/client/dev is a separate entry, so it adds nothing to a bundle that doesn’t import it. To try conditions without code, use the dev tools.

Examples

Playing a local room over a poor connection

A development build reads conditions from the page’s query string, so ?rtt=150 plays the game as a player far from the region would.

// lag.ts
import { connect } from "@irtio/client";
import { simulateNetwork, type DevConnectInit } from "@irtio/client/dev";

const query = new URLSearchParams(location.search);
const rtt = Number(query.get("rtt") ?? 0);
const init: DevConnectInit = rtt > 0 ? { dial: simulateNetwork({ rttMs: rtt, jitterMs: rtt / 10, loss: 0.02 }) } : {};

const room = await connect("main", init);
console.log(`playing with ${rtt} ms added, measured rtt ${room.rtt} ms`);

See also

Runtime availability

BrowsersNode
simulateNetwork()5.05.0