JavaScript/TypeScript SDK¶
The JavaScript/TypeScript SDK is compatible with mostly every platform:
- Browsers (Google Chrome, Firefox, Safari, Opera, Brave, etc.)
- Node.js
- Electron
- React Native
- Cocos Creator 3.0 (See instructions)
Usage¶
Including the JavaScript SDK in your project¶
This is the preffered method if you're using a build tool (webpack
, rollup
, or similar)
If you're not using a build tool, it is recommended to download the release binaries from GitHub Releases
Alternatively, you may include the distribution file directly by using unpkg. Make sure to replace the @x.x.x
portion of it with a version compatible with your server.
Connecting to server¶
import * as Colyseus from "colyseus.js"; // not necessary if included via <script> tag.
var client = new Colyseus.Client('ws://localhost:2567');
Joining to a room¶
client.joinOrCreate("room_name").then(room => {
console.log(room.sessionId, "joined", room.name);
}).catch(e => {
console.log("JOIN ERROR", e);
});
Room events¶
Room state has been updated:
Message broadcasted from server or directly to this client:
room.onMessage("message_type", (message) => {
console.log(room.sessionId, "received on", room.name, message);
});
Server error occurred:
The client left the room:
Strongly Typed State / Auto-completion¶
When using TypeScript, you can leverage strong types and editor auto-completion for the state.
You may include only the type of the state itself or the concrete implementation.
(The following examples are applicable to joinOrCreate
, create
, join
, joinById
, reconnect
and consumeSeatReservation
methods.)
Importing only the type
:¶
You may use import type
to import only the type of the state from your server code.
Importing the concrete implementation:¶
In some cases, you may want to import the concrete implementation, to be able to re-use methods implemented in the server in the client.