API Reference
Complete reference documentation for the Game On Dude! server SDK.
Server API
Core server class methods and configuration
Main server class that handles WebSocket connections and room management.
Signature
new GameOnServer(config: ServerConfig)Example
import { GameOnServer } from '@gameon/multiplayer-server';
const server = new GameOnServer({
port: 3000,
redis: {
host: 'localhost',
port: 6379
},
database: {
connectionString: process.env.DATABASE_URL
}
});
server.start();Register a room type that clients can create or join.
Signature
defineRoom<T extends Room>(name: string, roomClass: new () => T): voidExample
server.defineRoom('trivia', TriviaRoom);
server.defineRoom('battle', BattleRoom);Set a custom authentication handler for incoming connections.
Signature
onAuth(handler: (token: string) => Promise<AuthResult>): voidExample
server.onAuth(async (token) => {
const user = await verifyToken(token);
return { userId: user.id, username: user.name };
});Gracefully shut down the server, waiting for rooms to empty.
Signature
gracefulShutdown(timeout?: number): Promise<void>Example
process.on('SIGTERM', async () => {
await server.gracefulShutdown(30000);
process.exit(0);
});Room API
Base room class for creating game rooms
Base class for all game rooms. Extend this to create custom game logic.
Signature
abstract class Room<TState, TClient>Example
import { Room, Client } from '@gameon/multiplayer-server';
interface GameState {
players: Map<string, Player>;
phase: 'waiting' | 'playing' | 'ended';
}
class MyGameRoom extends Room<GameState> {
onCreate(options: RoomOptions) {
this.setState({
players: new Map(),
phase: 'waiting'
});
}
}Called when the room is created. Initialize your game state here.
Signature
onCreate(options: RoomOptions): void | Promise<void>Example
onCreate(options) {
this.maxClients = options.maxPlayers || 4;
this.setState({ round: 0, scores: {} });
this.setMetadata({ gameMode: options.mode });
}Called when a client joins the room.
Signature
onJoin(client: Client, options: JoinOptions): void | Promise<void>Example
onJoin(client, options) {
this.state.players.set(client.sessionId, {
name: options.username,
score: 0,
ready: false
});
this.broadcast('player_joined', { id: client.sessionId });
}Called when a client leaves the room.
Signature
onLeave(client: Client, consented: boolean): void | Promise<void>Example
async onLeave(client, consented) {
if (!consented) {
// Allow reconnection for 30 seconds
const reconnected = await this.allowReconnection(client, 30);
if (reconnected) return;
}
this.state.players.delete(client.sessionId);
}Register a handler for a specific message type.
Signature
onMessage<T>(type: string, handler: (client: Client, message: T) => void): voidExample
onCreate() {
this.onMessage('move', (client, data) => {
const player = this.state.players.get(client.sessionId);
player.x = data.x;
player.y = data.y;
});
this.onMessage('chat', (client, message) => {
this.broadcast('chat', {
from: client.sessionId,
text: message.text
});
});
}Send a message to all connected clients.
Signature
broadcast(type: string, message: any, options?: BroadcastOptions): voidExample
// Send to all clients
this.broadcast('game_start', { countdown: 3 });
// Send to all except one client
this.broadcast('player_moved', data, {
except: client
});Send a message to a specific client.
Signature
send(client: Client, type: string, message: any): voidExample
// Send private message to one client
this.send(client, 'your_cards', {
cards: player.hand
});Client Messages
Built-in message types and protocols
Automatic state synchronization between server and clients.
Signature
Message type: 'state_sync'Example
// Server-side: State changes are automatically synced
this.state.scores[playerId] = 100;
// Client-side (Unity): Listen for state changes
room.OnStateChange += (state) => {
UpdateScoreboard(state.scores);
};Built-in room lifecycle events.
Signature
join, leave, error, reconnectExample
// Unity client
room.OnJoin += () => Debug.Log("Joined room!");
room.OnLeave += (code) => Debug.Log($"Left: {code}");
room.OnError += (error) => Debug.LogError(error);Send and receive custom message types.
Signature
room.Send(type, data) / room.OnMessage(type, handler)Example
// Unity client: Send a message
room.Send("player_action", new {
action = "jump",
position = transform.position
});
// Unity client: Receive messages
room.OnMessage<ChatMessage>("chat", (message) => {
chatUI.AddMessage(message.from, message.text);
});TypeScript Types
Core type definitions
Configuration options for the server.
Signature
interface ServerConfigExample
interface ServerConfig {
port: number;
redis?: {
host: string;
port: number;
password?: string;
};
database?: {
connectionString: string;
};
cors?: {
origin: string | string[];
};
gracefulShutdownTimeout?: number;
}Represents a connected client.
Signature
interface ClientExample
interface Client {
sessionId: string;
auth: AuthData;
send(type: string, message: any): void;
leave(code?: number): void;
error(message: string): void;
}Options passed when creating a room.
Signature
interface RoomOptionsExample
interface RoomOptions {
maxClients?: number;
metadata?: Record<string, any>;
[key: string]: any;
}Options passed when a client joins a room.
Signature
interface JoinOptionsExample
interface JoinOptions {
username?: string;
team?: string;
[key: string]: any;
}Need More Help?
Check out our guides for step-by-step tutorials on building multiplayer games.