RoomClient: close event

Available since @irtio/client 5.0BrowsersNode

The close event of the RoomClient interface fires when the client’s connection to the room ends for good, and the client doesn’t reconnect.

Syntax

addEventListener("close", (event) => {})

Event type

A RoomCloseEvent. It extends Event and adds these properties:

code Read only
The close code, or 0 when connecting failed before any close.
reason Read only
The router’s or the room’s close reason, or "".
wasClean Read only
true when this client closed with close().
error Read only
The IrtError that ended the connection, unless the client closed it itself.

Description

close fires once, and readyState is "closed" from then on. It fires when:

  • The client called close(). code is 1000, reason is "", wasClean is true and error is undefined.
  • The router or the room closed the connection with a code the client doesn’t retry, such as 4004 for a new build or 4011 when the room hibernated on its own request. code and reason are the close’s, and error is named for the code.
  • The first connection failed: the room couldn’t be reached (NetworkError), timeout passed or an AbortSignal.timeout() signal aborted (TimeoutError), or another signal aborted (AbortError). code is 0. wasClean is false.

error is the same error connect() and ready reject with when the client closes before it was ready. Calls in flight reject when it closes.

A handoff that doesn’t keep this client closes it with close() once the new room’s client holds its state, so close fires with wasClean true before the handoff event.

Examples

Telling the player why they left

A clean close goes back to the menu. A room that hibernated on its own request gets a rejoin button rather than a reconnect loop, and a new build reloads the page.

// leaving.ts
import { CloseCode, connect, reloadForNewBuild } from "@irtio/client";

const room = await connect("https://rooms.irt.io/my-game/dungeon-4");

room.addEventListener("close", ({ wasClean, error }) => {
  if (wasClean || !error) return showMenu();
  if (error.name === "VersionError") return reloadForNewBuild();
  if (error.code === CloseCode.RoomHibernated) return offerRejoin();
  if (error.code === CloseCode.Kicked) return showMessage(`Removed from the room: ${error.reason}`);
  console.error(error);
  showMessage(error.message);
});

declare function showMenu(): void;
declare function offerRejoin(): void;
declare function showMessage(text: string): void;

Branch on error.name or error.code, never on error.message, which is for logs.

See also

Runtime availability

BrowsersNode
close event5.05.0