RoomClient: close() method

Available since @irtio/client 5.0BrowsersNode

The close() method of the RoomClient interface closes the connection for good, with close code 1000. The room takes it as the player leaving on purpose.

Syntax

close()

Parameters

None.

Return value

None (undefined).

Exceptions

None.

Description

close() sends this player’s unsent owner writes first, as flush() does, then closes the connection. Since the player left on purpose, their presence ends at once, with no grace, and the room’s onPlayerLeave() runs without waiting.

After close(), the client:

  • doesn’t reconnect
  • sets readyState to "closed"
  • fires the close event with code 1000, wasClean set to true and no error
  • rejects its calls in flight with an IrtError named NetworkError, since they may or may not have run

Called before the client is ready, close() makes ready reject with an IrtError named AbortError, with code 1000. To give up on connect() instead, pass it a signal and abort that. Calling close() on a closed client does nothing.

Examples

Leaving a match

A menu button leaves the match. The close listener tells a player who left apart from one whose connection ended for another reason.

// leave.ts
import { connect } from "@irtio/client";

const room = await connect("match-7");

room.addEventListener("close", (event) => {
  if (event.wasClean) console.log("You left the match.");
  else console.error(`The match ended: ${event.error?.message}`);
});

document.querySelector("#leave")!.addEventListener("click", () => room.close());

Cancelling a join

A player who changes their mind while the room is starting cancels the join. The client is constructed with new RoomClient rather than connect(), so the page holds it before it’s ready.

// cancel-join.ts
import { IrtError, RoomClient } from "@irtio/client";

const client = new RoomClient("match-7");
document.querySelector("#cancel")!.addEventListener("click", () => client.close());

try {
  const room = await client.ready;
  console.log(`Joined as ${room.player}`);
} catch (e) {
  if (e instanceof IrtError && e.name === "AbortError") console.log("Join cancelled.");
  else throw e;
}

See also

Runtime availability

BrowsersNode
close()5.05.0