RoomClient: close event
@irtio/client 5.0BrowsersNodeThe 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:
codeRead only- The close code, or 0 when connecting failed before any close.
reasonRead only- The router’s or the room’s close reason, or
"". wasCleanRead onlytruewhen this client closed withclose().errorRead only- The
IrtErrorthat 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().codeis 1000,reasonis"",wasCleanistrueanderrorisundefined. - 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.
codeandreasonare the close’s, anderroris named for the code. - The first connection failed: the room couldn’t be reached (
NetworkError),timeoutpassed or anAbortSignal.timeout()signal aborted (TimeoutError), or anothersignalaborted (AbortError).codeis 0.wasCleanisfalse.
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
RoomCloseEventRoomClient.close()reconnectingevent- Errors and close codes, for every code and error name
Runtime availability
| Browsers | Node | |
|---|---|---|
close event | 5.0 | 5.0 |