Sending & Receiving Messages
Once connected to a room, you can send and receive messages in real-time.
Sending Messages
Send messages to the room. Messages are encoded with MsgPack and can hold any JSON-serializable data.
//
// sending message with string type
//
room.send("move", { direction: "left"});
//
// sending message with number type
//
room.send(0, { direction: "left"});Backend: See Room → Message Handling for detailed documentation on receiving messages from the client.
Send Raw Bytes
For custom encoding, send a Uint8Array of raw bytes.
//
// sending message with number type
//
room.sendBytes(0, new Uint8Array([ 172, 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33 ]));
//
// sending message with string type
//
room.sendBytes("some-bytes", new Uint8Array([ 172, 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33 ]));The payload must be a Uint8Array. A plain number[] array silently sends an empty message, since the SDK reads .byteLength from the payload.
Receiving Messages
Listen for messages sent from the server.
room.onMessage("powerup", (message) => {
console.log("message received from server");
console.log(message);
});Backend: To send a message from the server to a client, use client.send() or room.broadcast().
Request/Response
Send a message and await the server’s reply. The server answers by returning a value from its matching message handler.
//
// Promise form: room.request(type, payload)
//
const profile = await room.request("get-profile", { userId: 42 });
//
// Override the default timeout (10s) per request
//
const result = await room.request("slow-task", { id }, { timeout: 30_000 });
//
// Callback form: pass a 3rd argument to room.send()
//
room.send("get-profile", { userId: 42 }, (profile, error) => {
if (error) { return console.error(error); }
console.log(profile);
});The promise rejects (or the callback receives an error) when the handler throws or no handler is registered for that type. Rejection also happens when the connection closes first, or when no reply arrives within the timeout. The default timeout is Room.defaultRequestTimeout (10000 ms), overridable per request via the timeout option.
The server may also deliberately reject a request via ctx.reject(reason): a business-logic “no”, distinct from an error. The rejection arrives as an Error with name: "rejected", and the server’s raw reason on its .reason property:
try {
await room.request("join-team", { team: "red" });
} catch (e: any) {
if (e.name === "rejected") {
console.log(e.reason); // => { code: "TEAM_FULL", team: "red" }
}
}Pass mode: "unreliable" in the options to send the request over the unreliable channel, when the transport has one. A genuine packet drop is then surfaced by the timeout.
Request/response is currently available in the JavaScript/TypeScript SDK.