### Install and Start Colyseus Server Source: https://github.com/colyseus/docs/blob/master/pages/learn/tutorial/babylonjs/hide-and-seek.mdx Run these commands in the terminal within the 'Server' directory to install dependencies and start the Colyseus server for the demo. ```bash cd Server npm install npm start ``` -------------------------------- ### Compile Haxe Example Project Source: https://github.com/colyseus/docs/blob/master/pages/getting-started/haxe.mdx Install necessary dependencies and compile the example project for the HTML5 target. ```sh git clone https://github.com/colyseus/colyseus-hx.git cd colyseus-hx/example/openfl # Install haxelib dependencies haxelib install openfl haxelib install lime haxelib install tink_http haxelib install tink_await haxelib install swf haxelib install colyseus-websocket # Compile the project haxelib run lime test project.xml html5 ``` -------------------------------- ### Configure package.json start script Source: https://github.com/colyseus/docs/blob/master/pages/learn/tutorial/phaser/basic-player-movement.mdx Add a start script to package.json for easier server execution. ```json // (...) "scripts": { "start": "parcel serve index.html", }, // (...) ``` -------------------------------- ### API Routes - Basic Example Source: https://github.com/colyseus/docs/blob/master/pages/server/http-routes.mdx Defines two API endpoints, GET /profile/:id and POST /profile/:id, using createEndpoint and createRouter. ```APIDOC ## GET /profile/:id ### Description Retrieves a user profile, optionally including additional data. ### Method GET ### Endpoint /profile/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the profile to retrieve. #### Query Parameters - **include** (string) - Optional - Specifies additional data to include in the response. ### Response #### Success Response (200) - **id** (string) - The ID of the profile. - **include** (string) - The value of the include query parameter, if provided. ### Request Example ```json { "example": "" } ``` ### Response Example ```json { "id": "user-123", "include": "friends" } ``` ## POST /profile/:id ### Description Updates a user profile with the provided name. ### Method POST ### Endpoint /profile/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the profile to update. #### Request Body - **name** (string) - Required - The new name for the profile. ### Response #### Success Response (201) - **id** (string) - The ID of the updated profile. - **name** (string) - The new name of the profile. ### Request Example ```json { "name": "John Doe" } ``` ### Response Example ```json { "id": "user-123", "name": "John Doe" } ``` ``` -------------------------------- ### Install runtime dependencies Source: https://github.com/colyseus/docs/blob/master/pages/learn/tutorial/phaser/basic-player-movement.mdx Install Phaser and the Colyseus SDK. ```sh npm install --save phaser @colyseus/sdk ``` -------------------------------- ### Install Dependencies Source: https://github.com/colyseus/docs/blob/master/pages/recipes/setup-server-from-scratch-typescript.mdx Install Colyseus and necessary development tools. ```sh npm i colyseus ``` ```sh npm i --save-dev typescript ts-node-dev ``` -------------------------------- ### Start development services Source: https://github.com/colyseus/docs/blob/master/pages/getting-started/discord-activity.mdx Commands to initialize the local development environment for the server and client. ```bash npm run start:server ``` ```bash npm run start:client ``` -------------------------------- ### Start Development Server with pnpm Source: https://github.com/colyseus/docs/blob/master/README.md Execute this command to launch the local development server. ```bash pnpm dev ``` -------------------------------- ### Installing Winston Source: https://github.com/colyseus/docs/blob/master/pages/server/logging.mdx Install the winston package via npm. ```sh npm install --save winston ``` -------------------------------- ### Create Dockerfile for Colyseus Project Source: https://github.com/colyseus/docs/blob/master/pages/deployment.mdx This Dockerfile sets up a Node.js environment for a Colyseus server. It installs dependencies, copies project files, exposes the default port, and defines the start command. Ensure `package.json` and `package-lock.json` are in the root. ```dockerfile FROM node:22 ENV PORT 2567 WORKDIR /usr/src/app # A wildcard is used to ensure both package.json AND package-lock.json are copied COPY package*.json ./ RUN npm ci # run this for production # npm ci --only=production COPY . . EXPOSE 2567 CMD [ "npm", "start" ] ``` -------------------------------- ### Installing Pino Source: https://github.com/colyseus/docs/blob/master/pages/server/logging.mdx Install the pino package via npm. ```sh npm install --save pino ``` -------------------------------- ### Install @colyseus/react Source: https://github.com/colyseus/docs/blob/master/pages/getting-started/react.mdx Install the @colyseus/react package using npm. ```bash npm install @colyseus/react ``` -------------------------------- ### Start Listening Source: https://github.com/colyseus/docs/blob/master/pages/server.mdx Binds the Transport layer to the specified port to start the server. ```APIDOC ## Start Listening ### Description Binds the [Transport](/server/transport) layer into the specified port, making the server available to accept connections. ### Method `server.listen(port: number, host?: string)` ### Endpoint N/A (Server configuration) ### Parameters #### Path Parameters - **port** (number) - Required - The port number to listen on. - **host** (string) - Optional - The host address to bind to. ### Request Example ```typescript filename="src/app.config.ts" import { defineServer } from "colyseus"; const server = defineServer({ // ... }); server.listen(2567); ``` ``` -------------------------------- ### Install pnpm globally Source: https://github.com/colyseus/docs/blob/master/pages/cloud/typescript-compilation-errors.mdx Install pnpm for monorepo management. ```sh npm install -g pnpm ``` -------------------------------- ### Install Basic Auth Source: https://github.com/colyseus/docs/blob/master/pages/tools/monitoring.mdx Install the express-basic-auth package to secure the monitoring route. ```sh npm install --save express-basic-auth ``` -------------------------------- ### Client Setup Source: https://github.com/colyseus/docs/blob/master/pages/sdk.mdx Initialize the Colyseus client to establish a connection to the server. ```APIDOC ## Client Setup The `Client` instance is your entry point to connect to the server. ### Request Example ```ts import { Client } from "@colyseus/sdk"; const client = new Client("http://localhost:2567"); // ... with full-stack type safety (optional) import type { server } from "../../server/src/app.config.ts"; const client = new Client("http://localhost:2567"); ``` ```cs using Colyseus; Client client = new Client("http://localhost:2567"); ``` ```lua local Colyseus = require("colyseus.sdk") local client = Colyseus.Client("http://localhost:2567"); ``` ```haxe import io.colyseus.Client; var client = new Client("http://localhost:2567"); ``` ```gdscript var client = Colyseus.Client.new("ws://localhost:2567") ``` ``` -------------------------------- ### View server output Source: https://github.com/colyseus/docs/blob/master/pages/learn/tutorial/phaser/basic-player-movement.mdx Expected output when starting the development server. ```txt > client@1.0.0 start > parcel serve index.html Server running at http://localhost:1234 ✨ Built in 6ms ``` -------------------------------- ### Complete Colyseus Client Example Source: https://github.com/colyseus/docs/blob/master/pages/room/reconnection.mdx A comprehensive example demonstrating how to initialize a Colyseus client, join or create a room, and handle various room events including state changes, drops, reconnections, and errors. ```typescript import { Client, CloseCode } from "colyseus.js"; const client = new Client("ws://localhost:2567"); async function joinGame() { const room = await client.joinOrCreate("game_room"); room.onStateChange((state) => { // Update game state updateGameUI(state); }); room.onDrop((code, reason) => { console.log(`Disconnected: ${code} - ${reason}`); showReconnectingUI(); }); room.onReconnect(() => { console.log("Reconnected!"); hideReconnectingUI(); }); room.onLeave((code, reason) => { console.log(`Left room: ${code}`); if (code === CloseCode.FAILED_TO_RECONNECT) { showError("Failed to reconnect. Please try again."); } // Clean up and return to menu cleanupGame(); }); room.onError((code, message) => { console.error(`Room error: ${code} - ${message}`); }); } ``` -------------------------------- ### Install @colyseus/traefik Source: https://github.com/colyseus/docs/blob/master/pages/scalability/traefik.mdx Install the Traefik integration module for Colyseus. ```sh npm install @colyseus/traefik ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/colyseus/docs/blob/master/README.md Run this command to install project dependencies using pnpm. ```bash pnpm i ``` -------------------------------- ### Install dependencies with pnpm Source: https://github.com/colyseus/docs/blob/master/pages/cloud/typescript-compilation-errors.mdx Install project dependencies using pnpm. ```sh pnpm install ``` -------------------------------- ### Initialize Colyseus Server Source: https://github.com/colyseus/docs/blob/master/pages/learn/tutorial/playcanvas.mdx Commands to scaffold and start a new Colyseus server project locally. ```sh npm init colyseus-app ./playcanvas-demo-server ``` ```sh cd playcanvas-demo-server npm start ``` -------------------------------- ### Start Colyseus Server Source: https://github.com/colyseus/docs/blob/master/pages/learn/tutorial/phaser/basic-player-movement.mdx Commands to navigate to the server directory and start the local development server. ```sh cd server npm start ``` -------------------------------- ### Install Colyseus Monitor Source: https://github.com/colyseus/docs/blob/master/pages/tools/monitoring.mdx Install the monitoring package via npm. ```sh npm install --save @colyseus/monitor ``` -------------------------------- ### Example ecosystem.config.js Source: https://github.com/colyseus/docs/blob/master/pages/cloud/troubleshooting.mdx Configuration file for PM2 to manage the application process. ```javascript const os = require('os'); module.exports = { apps : [{ name: "colyseus-app", script: 'build/index.js', time: true, watch: false, instances: os.cpus().length, exec_mode: 'fork', wait_ready: true, }], }; ``` -------------------------------- ### Install @colyseus/loadtest Source: https://github.com/colyseus/docs/blob/master/pages/tools/loadtest.mdx Install the load testing package as a development dependency. ```sh npm install --save-dev @colyseus/loadtest ``` -------------------------------- ### Install @colyseus/command Source: https://github.com/colyseus/docs/blob/master/pages/best-practices/command-pattern.mdx Install the @colyseus/command package using npm or yarn. ```sh npm install --save @colyseus/command ``` -------------------------------- ### Install @colyseus/auth Module Source: https://github.com/colyseus/docs/blob/master/pages/auth/module.mdx Install the @colyseus/auth module using npm or yarn. ```sh npm install --save @colyseus/auth ``` -------------------------------- ### Initialize Colyseus Server Source: https://github.com/colyseus/docs/blob/master/pages/learn/tutorial/babylonjs/intro.mdx Commands to scaffold a new Colyseus project and start the development server. ```sh npm create colyseus-app@latest ./babylonjs-multiplayer-server ``` ```sh cd babylonjs-multiplayer-server npm start ``` -------------------------------- ### Install Redis Presence package Source: https://github.com/colyseus/docs/blob/master/pages/server/presence.mdx Install the required dependency for multi-process deployments. ```sh npm install --save @colyseus/redis-presence ``` -------------------------------- ### Define Main Server Entry Point Source: https://github.com/colyseus/docs/blob/master/pages/recipes/setup-server-from-scratch-typescript.mdx Basic setup for the main.ts file to initialize the Colyseus server. ```ts import { defineServer } from "colyseus" const port = parseInt(process.env.PORT, 10) || 3000 const server = defineServer({/* ... */}) server.listen(port) console.log(`[GameServer] Listening on Port: ${port}`) ``` -------------------------------- ### Server Lifecycle Commands Source: https://github.com/colyseus/docs/blob/master/pages/recipes/setup-server-from-scratch-typescript.mdx Commands to start, develop, build, and run the server in production. ```sh npm start ``` ```sh npm run start:dev ``` ```sh npm run build ``` ```sh npm run start:prod ``` -------------------------------- ### Install Colyseus Testing Package Source: https://github.com/colyseus/docs/blob/master/pages/tools/unit-testing.mdx Install the testing utility package as a development dependency. ```bash npm install --save-dev @colyseus/testing ``` -------------------------------- ### Install Colyseus Haxe SDK Source: https://github.com/colyseus/docs/blob/master/pages/getting-started/haxe.mdx Use the haxelib package manager to install the Colyseus library. ```sh haxelib install colyseus ``` -------------------------------- ### Install @colyseus/tools Source: https://github.com/colyseus/docs/blob/master/pages/migrating/0.15.mdx Replace the deprecated @colyseus/arena package with @colyseus/tools. ```sh npm install --save @colyseus/tools ``` -------------------------------- ### Install URL Polyfill via NPM Source: https://github.com/colyseus/docs/blob/master/pages/getting-started/wechat.mdx Install the `url-polyfill` package using NPM if you are using a build system. This is required because WeChat's JavaScript runtime does not provide the standard `URL` object. ```bash npm install --save url-polyfill ``` -------------------------------- ### Express Routes - Basic Example Source: https://github.com/colyseus/docs/blob/master/pages/server/http-routes.mdx Shows how to integrate Colyseus with an existing Express application to define routes. ```APIDOC ## GET /hello ### Description A simple Express route that returns a "hello world" JSON response. ### Method GET ### Endpoint /hello ### Response #### Success Response (200) - **hello** (string) - A greeting message. ### Response Example ```json { "hello": "world" } ``` ## POST /profile ### Description An Express route that accepts a JSON request body and returns the received data. ### Method POST ### Endpoint /profile ### Parameters #### Request Body - **(any)** - Accepts any JSON object. ### Response #### Success Response (200) - **received** (object) - The JSON data received in the request body. ### Response Example ```json { "received": { "key": "value" } } ``` ``` -------------------------------- ### API Routes - Middleware Example Source: https://github.com/colyseus/docs/blob/master/pages/server/http-routes.mdx Demonstrates how to use middleware for authentication and shared logic in API routes. ```APIDOC ## GET /secure ### Description An example of a secure endpoint that requires authentication via middleware. ### Method GET ### Endpoint /secure ### Parameters #### Request Headers - **authorization** (string) - Required - The authentication token. ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the request was successful. - **userId** (string) - The ID of the authenticated user. #### Response Headers - **X-User** (string) - The ID of the authenticated user. - **Set-Cookie** (string) - A session cookie. ### Response Example ```json { "ok": true, "userId": "user-123" } ``` ``` -------------------------------- ### Start development server Source: https://github.com/colyseus/docs/blob/master/pages/learn/tutorial/phaser/basic-player-movement.mdx Commands to run the Parcel development server. ```sh npx parcel serve index.html ``` ```sh npm start ``` -------------------------------- ### Initialize frontend project Source: https://github.com/colyseus/docs/blob/master/pages/learn/tutorial/phaser/basic-player-movement.mdx Commands to create the client directory and initialize the npm project. ```sh mkdir client cd client npm init -y ``` -------------------------------- ### LobbyRoom Class Example Source: https://github.com/colyseus/docs/blob/master/pages/concepts.mdx An example of a lobby room used as a waiting area. It handles player readiness and initiates game starting when all players are ready. ```typescript class LobbyRoom extends Room { state = new LobbyState(); onCreate() { this.onMessage("ready", (client) => { const player = this.state.players.get(client.sessionId); player.isReady = true; if (this.allPlayersReady()) { this.broadcast("gameStarting"); // Transfer players to game room } }); } } ``` -------------------------------- ### Install Bun WebSockets package Source: https://github.com/colyseus/docs/blob/master/pages/server/transport/bun-websockets.mdx Use the Bun package manager to add the transport layer dependency. ```sh bun add @colyseus/bun-websockets ``` -------------------------------- ### GameRoom Class Example Source: https://github.com/colyseus/docs/blob/master/pages/concepts.mdx A common pattern for a game room handling matches. Initializes state, sets metadata, and manages client joins. Locks the room when full and starts the game. ```typescript class GameRoom extends Room { maxClients = 4; state = new GameState(); onCreate(options) { this.setMetadata({ map: options.map }); } onJoin(client) { this.state.players.set(client.sessionId, new Player()); if (this.clients.length === this.maxClients) { this.lock(); // Prevent more joins this.startGame(); } } } ``` -------------------------------- ### Server Startup Output Source: https://github.com/colyseus/docs/blob/master/pages/learn/tutorial/phaser/basic-player-movement.mdx Expected console output upon successful server initialization. ```txt ✅ development.env loaded. ✅ Express initialized ⚔️ Listening on http://localhost:2567 ``` -------------------------------- ### Start Server Listening Source: https://github.com/colyseus/docs/blob/master/pages/server.mdx Binds the transport layer to the specified port to begin accepting connections. ```ts import { defineServer } from "colyseus"; const server = defineServer({ // ... }); server.listen(2567); ``` -------------------------------- ### Complete Server-Side Room Implementation Source: https://github.com/colyseus/docs/blob/master/pages/room/reconnection.mdx A full example demonstrating the integration of onCreate, onJoin, onDrop, onReconnect, and onLeave. ```typescript import { Room, Client, CloseCode } from "colyseus"; import { MyState, Player } from "./MyState"; class GameRoom extends Room<{ state: MyState }> { onCreate(options: any) { this.setState(new MyState()); } onJoin(client: Client, options: any) { const player = new Player(); player.connected = true; this.state.players.set(client.sessionId, player); } onDrop(client: Client, code: number) { console.log(`Client ${client.sessionId} dropped (code: ${code})`); // Allow reconnection for 30 seconds this.allowReconnection(client, 30); // Mark player as disconnected (but don't remove them) const player = this.state.players.get(client.sessionId); if (player) { player.connected = false; } } onReconnect(client: Client) { console.log(`Client ${client.sessionId} reconnected!`); // Restore player connection status const player = this.state.players.get(client.sessionId); if (player) { player.connected = true; } } onLeave(client: Client, code: number) { console.log(`Client ${client.sessionId} left permanently (code: ${code})`); // Now it's safe to remove the player this.state.players.delete(client.sessionId); } } ``` -------------------------------- ### Initialize Project Directory Source: https://github.com/colyseus/docs/blob/master/pages/recipes/setup-server-from-scratch-typescript.mdx Commands to create and enter a new project directory. ```sh mkdir colyseusServer ``` ```sh cd colyseusServer ``` -------------------------------- ### Run Test Server Locally Source: https://github.com/colyseus/docs/blob/master/pages/getting-started/defold.mdx Commands to clone and start the Colyseus test server for local development. ```sh git clone https://github.com/colyseus/sdks-test-server cd sdks-test-server npm install npm start ``` -------------------------------- ### Initialize NPM Source: https://github.com/colyseus/docs/blob/master/pages/recipes/setup-server-from-scratch-typescript.mdx Initialize the project with default npm options. ```sh npm init ``` -------------------------------- ### Colyseus Client Quick Example Source: https://github.com/colyseus/docs/blob/master/pages/getting-started/typescript.mdx Connect to a Colyseus server, join or create a room, and set up listeners for state changes and messages. Use `https://` or `wss://` for secure connections in production. ```ts import { Client, Callbacks } from "@colyseus/sdk"; const client = new Client("http://localhost:2567"); // Join or create a room const room = await client.joinOrCreate("my_room"); // Get state callbacks handler const callbacks = Callbacks.get(room); // Listen for changes on a state property callbacks.listen("currentTurn", (currentValue, previousValue) => { console.log("Turn changed:", previousValue, "->", currentValue); }); // Listen for entities being added to a collection callbacks.onAdd("players", (player, sessionId) => { console.log("Player joined:", sessionId); // Listen for changes on nested properties callbacks.listen(player, "hp", (currentHp, previousHp) => { console.log("Player", sessionId, "hp:", currentHp); }); }); // Listen for entities being removed from a collection callbacks.onRemove("players", (player, sessionId) => { console.log("Player left:", sessionId); }); // Send a message to the server room.send("move", { x: 10, y: 20 }); // Listen for messages from the server room.onMessage("chat", (message) => { console.log("Chat:", message); }); ``` -------------------------------- ### Create Colyseus App with Node.js Source: https://github.com/colyseus/docs/blob/master/pages/getting-started.mdx Use npm to create a new Colyseus project, navigate into the directory, and start the server. This is the standard way to initialize a Colyseus application. ```bash # Create a new Colyseus project npm create colyseus-app@latest ./my-server # Enter the project directory cd my-server # Run the server npm start ``` -------------------------------- ### Connect and Interact with Room Source: https://github.com/colyseus/docs/blob/master/pages/getting-started/defold.mdx Example of initializing a client, joining a room, and setting up state and message listeners in a Defold script. ```lua local ColyseusSDK = require("colyseus.sdk") local client local room local callbacks function init(self) client = ColyseusSDK.Client("ws://localhost:2567") client:join_or_create("my_room", {}, function(err, _room) if err then print("JOIN ERROR: " .. err) return end room = _room print("Joined room: " .. room.id) -- Get state callbacks handler callbacks = ColyseusSDK.callbacks(room) -- Listen for changes on a state property callbacks:listen("currentTurn", function(currentValue, previousValue) print("Turn changed: " .. tostring(previousValue) .. " -> " .. tostring(currentValue)) end) -- Listen for players being added callbacks:on_add("players", function(player, sessionId) print("Player joined: " .. sessionId) callbacks:listen(player, "hp", function(currentHp, previousHp) print("Player " .. sessionId .. " hp: " .. tostring(currentHp)) end) end) -- Listen for players being removed callbacks:on_remove("players", function(player, sessionId) print("Player left: " .. sessionId) end) -- Send a message to the server room:send("move", { x = 10, y = 20 }) -- Listen for messages from the server room:on_message("chat", function(message) print("Chat: " .. message) end) room:on_leave(function(code) print("Left room: " .. code) end) end) end ``` -------------------------------- ### Install development dependencies Source: https://github.com/colyseus/docs/blob/master/pages/learn/tutorial/phaser/basic-player-movement.mdx Install Parcel and TypeScript as development dependencies. ```sh npm install --save-dev parcel typescript ``` -------------------------------- ### Build Native SDK from Source Source: https://github.com/colyseus/docs/blob/master/pages/getting-started/native-sdk.mdx Clone the repository and build the Native SDK using Zig. The output includes libraries and headers. ```sh git clone https://github.com/colyseus/native-sdk.git cd native-sdk zig build ``` -------------------------------- ### Colyseus Native C SDK Quick Example Source: https://github.com/colyseus/docs/blob/master/pages/getting-started/native-sdk.mdx Connect to a server, join a room, listen for state changes, send messages, and handle cleanup using the native C SDK. Ensure 'my_room_state.h' is generated by the schema compiler. ```c #include #include #include #include #include #include #include #include "my_room_state.h" // Generated schema header static colyseus_client_t* client = NULL; static colyseus_room_t* room = NULL; static colyseus_callbacks_t* callbacks = NULL; // --- Room event handlers --- static void on_join(void* userdata) { printf("Joined room! Session: %s\n", colyseus_room_get_session_id(room)); // Access the decoded state my_room_state_t* state = (my_room_state_t*)colyseus_room_get_state(room); // Create callbacks manager for state change listening callbacks = colyseus_callbacks_create(room->serializer->decoder); // Listen for players being added to the map colyseus_callbacks_on_add(callbacks, state, "players", on_player_add, NULL, true); // Listen for players being removed colyseus_callbacks_on_remove(callbacks, state, "players", on_player_remove, NULL); } static void on_state_change(void* userdata) { // Called every time the room state is updated } static void on_error(int code, const char* message, void* userdata) { printf("Room error (%d): %s\n", code, message); } static void on_leave(int code, const char* reason, void* userdata) { printf("Left room (%d): %s\n", code, reason ? reason : "unknown"); } // --- State change callbacks --- static void on_player_add(void* value, void* key, void* userdata) { player_t* player = (player_t*)value; const char* session_id = (const char*)key; printf("Player joined: %s (x=%.1f, y=%.1f)\n", session_id, player->x, player->y); // Listen for changes on individual player properties colyseus_callbacks_listen(callbacks, player, "x", on_player_x_change, NULL, false); } static void on_player_remove(void* value, void* key, void* userdata) { const char* session_id = (const char*)key; printf("Player left: %s\n", session_id); } static void on_player_x_change(void* current, void* previous, void* userdata) { double x = *(double*)current; printf("Player x changed to: %.1f\n", x); } // --- Matchmaking callback --- static void on_room_success(colyseus_room_t* joined_room, void* userdata) { room = joined_room; // Set state schema type (must be done before event handlers) colyseus_room_set_state_type(room, &my_room_state_vtable); // Register room event handlers colyseus_room_on_join(room, on_join, NULL); colyseus_room_on_state_change(room, on_state_change, NULL); colyseus_room_on_error(room, on_error, NULL); colyseus_room_on_leave(room, on_leave, NULL); } static void on_matchmaking_error(int code, const char* message, void* userdata) { printf("Failed to join: %s\n", message); } // --- Main --- int main(void) { // Create settings colyseus_settings_t* settings = colyseus_settings_create(); colyseus_settings_set_address(settings, "localhost"); colyseus_settings_set_port(settings, "2567"); // Create client client = colyseus_client_create(settings); // Join or create a room colyseus_client_join_or_create( client, "my_room", "{}", on_room_success, on_matchmaking_error, NULL ); // Main loop (integrate with your engine's loop) while (running) { // Your engine's frame update here... } // Cleanup if (callbacks) colyseus_callbacks_free(callbacks); if (room) { colyseus_room_leave(room, true); colyseus_room_free(room); } if (client) colyseus_client_free(client); colyseus_settings_free(settings); return 0; } ``` -------------------------------- ### Configure Client Settings Source: https://github.com/colyseus/docs/blob/master/pages/getting-started/native-sdk.mdx Create and configure client settings, including address, port, security (WSS), and custom headers. ```c colyseus_settings_t* settings = colyseus_settings_create(); colyseus_settings_set_address(settings, "example.com"); colyseus_settings_set_port(settings, "443"); colyseus_settings_set_secure(settings, true); // Use WSS // Custom headers colyseus_settings_add_header(settings, "Authorization", "Bearer token123"); colyseus_client_t* client = colyseus_client_create(settings); ``` -------------------------------- ### Install Playground Package Source: https://github.com/colyseus/docs/blob/master/pages/tools/playground.mdx Install the Colyseus Playground package using npm or yarn. ```sh npm install --save @colyseus/playground ``` -------------------------------- ### Initialize Colyseus Server Source: https://github.com/colyseus/docs/blob/master/pages/learn/tutorial/phaser/basic-player-movement.mdx Command to scaffold a new Colyseus server project. ```sh npm init colyseus-app ./server ``` -------------------------------- ### Initialize Colyseus App Source: https://github.com/colyseus/docs/blob/master/pages/server.mdx Use the CLI command to scaffold a new Colyseus project structure. ```sh npm create colyseus-app@latest ./my-server ``` -------------------------------- ### Discord OAuth Provider Example Source: https://github.com/colyseus/docs/blob/master/pages/auth/module.mdx Example configuration for adding Discord as an OAuth provider. ```APIDOC To enable Discord authentication, you must create a new application at [Discord Developer Portal](https://discord.com/developers/applications). Under the _"Settings -> OAuth2"_ you will find the Client ID (`key`) and Client Secret (`secret`), that must be used to configure the provider: ```ts filename="src/config/auth.ts" auth.oauth.addProvider('discord', { key: "XXXXXXXXXXXXXXXXXX", // Client ID secret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", // Client Secret scope: ['identify', 'email'], }); ``` You will also need to configure the "Redirect URL" so Discord can redirect the user back to your application after authentication. The URL must be in the following format: ``` https://[YOUR-DOMAIN]/auth/provider/discord/callback ``` ``` -------------------------------- ### Initialize Test Server Source: https://github.com/colyseus/docs/blob/master/pages/tools/unit-testing.mdx Boot the test server and connect simulated clients using Mocha or Jest frameworks. ```typescript import { ColyseusTestServer, boot } from "@colyseus/testing"; // import your "app.config.ts" file here. import appConfig from "../src/app.config"; describe("testing your Colyseus app", () => { let colyseus: ColyseusTestServer; before(async () => colyseus = await boot(appConfig)); after(async () => colyseus.shutdown()); beforeEach(async () => await colyseus.cleanup()); it("connecting into a room", async() => { // `room` is the backend Room instance reference. const room = await colyseus.createRoom("my_room", {}); // `client1` is the frontend `Room` instance reference (from the JavaScript SDK) const client1 = await colyseus.connectTo(room); // make your assertions assert.strictEqual(client1.sessionId, room.clients[0].sessionId); }); }); ``` ```typescript import { ColyseusTestServer, boot } from "@colyseus/testing"; // import your "app.config.ts" file here. import appConfig from "../src/app.config"; describe("testing your Colyseus app", () => { let colyseus: ColyseusTestServer; beforeAll(async () => colyseus = await boot(appConfig)); afterAll(async () => colyseus.shutdown()); beforeEach(async () => await colyseus.cleanup()); it("connecting into a room", async() => { // `room` is the backend Room instance reference. const room = await colyseus.createRoom("my_room", {}); // `client1` is the frontend `Room` instance reference (from the JavaScript SDK) const client1 = await colyseus.connectTo(room); // make your assertions expect(client1.sessionId).toEqual(room.clients[0].sessionId); }); }); ``` -------------------------------- ### Install H3Transport dependency Source: https://github.com/colyseus/docs/blob/master/pages/server/transport/webtransport.mdx Install the required package to enable WebTransport support in your Colyseus project. ```sh npm install --save @colyseus/h3-transport ``` -------------------------------- ### Initialize Colyseus Client Source: https://github.com/colyseus/docs/blob/master/pages/sdk.mdx Create a client instance to establish a connection to the Colyseus server. ```ts import { Client } from "@colyseus/sdk"; const client = new Client("http://localhost:2567"); // ... with full-stack type safety (optional) import type { server } from "../../server/src/app.config.ts"; const client = new Client("http://localhost:2567"); ``` ```cs using Colyseus; Client client = new Client("http://localhost:2567"); ``` ```lua local Colyseus = require("colyseus.sdk") local client = Colyseus.Client("http://localhost:2567"); ``` ```hx import io.colyseus.Client; var client = new Client("http://localhost:2567"); ``` ```gdscript var client = Colyseus.Client.new("ws://localhost:2567") ``` -------------------------------- ### Configure Backend for Email/Password Sign In Source: https://github.com/colyseus/docs/blob/master/pages/auth/module.mdx Implement the backend logic for signing in users with email and password. This example shows how to find a user by email. ```typescript import { auth } from "@colyseus/auth"; // ... auth.settings.onFindUserByEmail = async function (email) { return await User.query().selectAll().where("email", "=", email).executeTakeFirst(); } ``` -------------------------------- ### Configure package.json Source: https://github.com/colyseus/docs/blob/master/pages/recipes/setup-server-from-scratch-typescript.mdx Update the main entry point and scripts for building and running the server. ```json { "main": "dist/main.js", "scripts": { "build": "tsc", "start": "ts-node src/main.ts", "start:dev": "ts-node-dev --watch \"src/**/*\" --respawn --transpile-only src/main.ts ", "start:prod": "node dist/main.js", "test": "echo \"Error: no test specified\" && exit 1" }, } ``` -------------------------------- ### Install uWebSockets Transport for Express v4 Source: https://github.com/colyseus/docs/blob/master/pages/server/transport/uwebsockets.mdx Install the uWebSockets transport package for Express v4 using npm. ```sh npm install --save @colyseus/uwebsockets-transport@^1.4.1 ``` -------------------------------- ### Create index.ts entrypoint Source: https://github.com/colyseus/docs/blob/master/pages/learn/tutorial/phaser/basic-player-movement.mdx Initialize the Phaser game instance and define the game scene. ```ts import Phaser from "phaser"; // custom scene class export class GameScene extends Phaser.Scene { preload() { // preload scene } create() { // create scene } update(time: number, delta: number): void { // game loop } } // game config const config: Phaser.Types.Core.GameConfig = { type: Phaser.AUTO, width: 800, height: 600, backgroundColor: '#b6d53c', parent: 'phaser-example', physics: { default: "arcade" }, pixelArt: true, scene: [ GameScene ], }; // instantiate the game const game = new Phaser.Game(config); ``` -------------------------------- ### Install uWebSockets Transport for Express v5 Source: https://github.com/colyseus/docs/blob/master/pages/server/transport/uwebsockets.mdx Install the uWebSockets transport package for Express v5 using npm. ```sh npm install --save @colyseus/uwebsockets-transport@^2.0.1 ``` -------------------------------- ### Install Redis Driver for Colyseus Source: https://github.com/colyseus/docs/blob/master/pages/server/driver.mdx Install the Redis driver package using npm or yarn. This is required for using the Redis driver. ```sh npm install --save @colyseus/redis-driver ``` -------------------------------- ### Add Defold Dependencies Source: https://github.com/colyseus/docs/blob/master/pages/getting-started/defold.mdx Add these URLs to the Dependencies section of your game.project file. ```txt https://github.com/colyseus/colyseus-defold/archive/0.17.zip ``` ```txt https://github.com/defold/extension-websocket/archive/4.2.1.zip ``` -------------------------------- ### Persistent Room Example Source: https://github.com/colyseus/docs/blob/master/pages/concepts.mdx An example of a persistent room that remains active even when empty. It loads state on creation and saves it before disposal. ```typescript class WorldRoom extends Room { autoDispose = false; // Don't destroy when empty onCreate() { // Load world state from database this.loadWorldState(); } onDispose() { // Save before shutting down this.saveWorldState(); } } ``` -------------------------------- ### Install Colyseus SDK via npm Source: https://github.com/colyseus/docs/blob/master/pages/getting-started/typescript.mdx Install the Colyseus SDK using npm. This command adds the necessary package to your project dependencies. ```sh npm install --save @colyseus/sdk ``` -------------------------------- ### Get Local Room Instance by ID Source: https://github.com/colyseus/docs/blob/master/pages/matchmaker.mdx Get the actual Room instance if it exists in the current process. Returns undefined if the room is not local. ```typescript const room = await matchMaker.getLocalRoomById("xxxxxxxxx"); room.clients[0].send("hello", "world"); ``` -------------------------------- ### Deploy Application via CLI Source: https://github.com/colyseus/docs/blob/master/pages/cloud.mdx Execute the deployment command to initiate the browser-based authentication and deployment process. ```sh npx @colyseus/cloud deploy ``` -------------------------------- ### Install Drizzle Driver for Colyseus Source: https://github.com/colyseus/docs/blob/master/pages/server/driver.mdx Install the Drizzle driver package using npm or yarn. This is required for using the PostgreSQL driver with Drizzle ORM. ```sh npm install --save @colyseus/drizzle-driver ``` -------------------------------- ### Player Schema C Struct Example Source: https://github.com/colyseus/docs/blob/master/pages/getting-started/native-sdk.mdx Example of a C struct generated for a 'Player' schema, including base struct, field definitions, and vtable. ```c typedef struct { colyseus_schema_t __base; // Must be the first field double x; double y; bool isBot; bool disconnected; } player_t; static const colyseus_field_t player_fields[] = { {0, "x", COLYSEUS_FIELD_NUMBER, "number", offsetof(player_t, x), NULL, NULL}, {1, "y", COLYSEUS_FIELD_NUMBER, "number", offsetof(player_t, y), NULL, NULL}, {2, "isBot", COLYSEUS_FIELD_BOOLEAN, "boolean", offsetof(player_t, isBot), NULL, NULL}, {3, "disconnected", COLYSEUS_FIELD_BOOLEAN, "boolean", offsetof(player_t, disconnected), NULL, NULL}, }; static const colyseus_schema_vtable_t player_vtable = { "Player", sizeof(player_t), (colyseus_schema_t* (*)(void))player_create, player_destroy, player_fields, 4 }; ``` -------------------------------- ### Display schema-codegen help Source: https://github.com/colyseus/docs/blob/master/pages/sdk/state-sync-callbacks.mdx Run this command to see the available options and usage instructions for the schema-codegen tool. ```sh npx schema-codegen --help ``` -------------------------------- ### Install PM2 Process Manager Source: https://github.com/colyseus/docs/blob/master/pages/scalability.mdx Install the PM2 process manager globally using npm. PM2 is recommended for managing multiple Node.js application instances. ```bash npm install -g pm2 ``` -------------------------------- ### Lock Room on Game Start Source: https://github.com/colyseus/docs/blob/master/pages/concepts.mdx Programmatically lock a room when a game starts to prevent new players from joining mid-game. Locked rooms are not listed in `getAvailableRooms()`. ```typescript startGame() { // Lock the room when the game starts this.lock(); } ``` -------------------------------- ### Test HTTP GET Route Source: https://github.com/colyseus/docs/blob/master/pages/tools/unit-testing.mdx Tests an HTTP GET route of the Colyseus server using the provided HTTP client. It asserts the response data and headers. ```typescript it("should get json data", async () => { const response = await colyseus.http.get("/"); // "data" is the response body assert.deepStrictEqual({ success: true }, response.data); // access to response headers. assert.strictEqual('header value', response.headers['some-header']); }); ``` -------------------------------- ### Configure Backend for Email/Password Registration Source: https://github.com/colyseus/docs/blob/master/pages/auth/module.mdx Implement the backend logic for registering users with email and password. This example shows how to find a user by email and insert a new user into the database. ```typescript import { auth } from "@colyseus/auth"; // ... auth.settings.onFindUserByEmail = async function (email) { return await User.query().selectAll().where("email", "=", email).executeTakeFirst(); } auth.settings.onRegisterWithEmailAndPassword = async function (email, password, options) { return await User.insert({ name, email, password, }); } ``` -------------------------------- ### Install Cloudflared for Local Testing Source: https://github.com/colyseus/docs/blob/master/pages/payments/xsolla.mdx Install the Cloudflared CLI globally using npm. This tool is used to tunnel your local server to a public URL for testing webhooks. ```bash npm install -g cloudflared ``` -------------------------------- ### Start Colyseus Processes with PM2 Source: https://github.com/colyseus/docs/blob/master/pages/scalability.mdx Start your Colyseus application using PM2 with the defined ecosystem configuration. This command will launch multiple instances based on your 'ecosystem.config.js' file. ```bash pm2 start ecosystem.config.js ``` -------------------------------- ### Start Cloudflared Tunnel for Local Server Source: https://github.com/colyseus/docs/blob/master/pages/payments/xsolla.mdx Start a Cloudflared tunnel to expose your local Colyseus server running on http://localhost:2567 to the internet. This provides a public URL for Xsolla to send webhook events. ```bash npx cloudflared tunnel --url http://localhost:2567 ```