API Reference

Complete reference documentation for the Game On Dude! server SDK.

Server API

Core server class methods and configuration

GameOnServerclass

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();
server.defineRoommethod

Register a room type that clients can create or join.

Signature

defineRoom<T extends Room>(name: string, roomClass: new () => T): void

Example

server.defineRoom('trivia', TriviaRoom);
server.defineRoom('battle', BattleRoom);
server.onAuthmethod

Set a custom authentication handler for incoming connections.

Signature

onAuth(handler: (token: string) => Promise<AuthResult>): void

Example

server.onAuth(async (token) => {
  const user = await verifyToken(token);
  return { userId: user.id, username: user.name };
});
server.gracefulShutdownmethod

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

Roomclass

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'
    });
  }
}
room.onCreatelifecycle

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 });
}
room.onJoinlifecycle

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 });
}
room.onLeavelifecycle

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);
}
room.onMessagemethod

Register a handler for a specific message type.

Signature

onMessage<T>(type: string, handler: (client: Client, message: T) => void): void

Example

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
    });
  });
}
room.broadcastmethod

Send a message to all connected clients.

Signature

broadcast(type: string, message: any, options?: BroadcastOptions): void

Example

// Send to all clients
this.broadcast('game_start', { countdown: 3 });

// Send to all except one client
this.broadcast('player_moved', data, {
  except: client
});
room.sendmethod

Send a message to a specific client.

Signature

send(client: Client, type: string, message: any): void

Example

// Send private message to one client
this.send(client, 'your_cards', {
  cards: player.hand
});

Client Messages

Built-in message types and protocols

State Syncprotocol

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);
};
Room Eventsprotocol

Built-in room lifecycle events.

Signature

join, leave, error, reconnect

Example

// Unity client
room.OnJoin += () => Debug.Log("Joined room!");
room.OnLeave += (code) => Debug.Log($"Left: {code}");
room.OnError += (error) => Debug.LogError(error);
Custom Messagesprotocol

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

ServerConfiginterface

Configuration options for the server.

Signature

interface ServerConfig

Example

interface ServerConfig {
  port: number;
  redis?: {
    host: string;
    port: number;
    password?: string;
  };
  database?: {
    connectionString: string;
  };
  cors?: {
    origin: string | string[];
  };
  gracefulShutdownTimeout?: number;
}
Clientinterface

Represents a connected client.

Signature

interface Client

Example

interface Client {
  sessionId: string;
  auth: AuthData;
  send(type: string, message: any): void;
  leave(code?: number): void;
  error(message: string): void;
}
RoomOptionsinterface

Options passed when creating a room.

Signature

interface RoomOptions

Example

interface RoomOptions {
  maxClients?: number;
  metadata?: Record<string, any>;
  [key: string]: any;
}
JoinOptionsinterface

Options passed when a client joins a room.

Signature

interface JoinOptions

Example

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.