RoomClient: close() method
@irtio/client 5.0BrowsersNodeThe 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
readyStateto"closed" - fires the
closeevent with code 1000,wasCleanset totrueand noerror - rejects its calls in flight with an
IrtErrornamedNetworkError, 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
closeeventRoomClient.readyStateRoom.kick(), for the room closing a connection- Errors and close codes
Runtime availability
| Browsers | Node | |
|---|---|---|
close() | 5.0 | 5.0 |