WebSocket API Documentation
Introduction
The Matchmake WebSocket API provides real-time, bidirectional communication for client authentication, app management, and lobby operations. This documentation outlines how to connect to and use the API using TypeScript and the "ws" WebSocket library.
Getting Started
Installation
First, install the "ws" WebSocket library and its TypeScript types:
npm install ws @types/ws
Connection Setup
Import the necessary modules and set up the connection:
import WebSocket from 'ws';const headers = {'X-Authorization': "Bearer YOUR_API_KEY_HERE"};const socket: WebSocket = await new WebSocket(serverUrl, undefined, { headers });socket.onopen = () => {// Send auth:register_player_sessionconsole.log('Connected to WebSocket server');};
Authentication
Player Authentication
To authenticate a player, send a message to the "auth:register_player_session" channel:
const authMessage = {topic: "app:auth",event: "phx_join",ref: Math.random().toString(36).substring(2, 15),payload: {player_slug: `player_${Math.random().toString(36).substring(3, 10)}`,ip_address: "127.0.0.1:8000"}};socket.send(JSON.stringify(authMessage));socket.onmessage = (event) => {const response = JSON.parse(event.data);if (response.topic === 'app:auth') {if (response.status === 'ok') {console.log('Authentication successful', response.payload);// Store session token}}};
App Channel
Joining the App Channel
After authentication, join the app channel to access matchmaking configurations:
const joinAppChannel = {topic: "app:lobby",event: "phx_join",payload: {player_session_token: sessionToken}};socket.send(JSON.stringify(joinAppChannel));
Lobby Channel
Managing Lobbies
Handle lobby operations including creation, joining, and updates:
// Create a new lobbyconst createLobby = {topic: "app:lobby",event: "create_lobby",payload: {config_id: 1,max_players: 4}};// Join an existing lobbyconst joinLobby = {topic: "app:lobby",event: "join_lobby",payload: {lobby_id: "lobby_123"}};socket.send(JSON.stringify(createLobby));
Error Handling
Implement comprehensive error handling for various scenarios:
socket.onmessage = (event) => {const response = JSON.parse(event.data);if (response.status === 'error') {switch (response.code) {case 'auth_failed':console.error('Authentication failed');// Handle authentication errorbreak;case 'invalid_lobby':console.error('Invalid lobby operation');// Handle lobby errorbreak;default:console.error('Unknown error', response);}}};
Best Practices
Follow these best practices for optimal implementation:
- Implement heartbeat mechanism to maintain connection
- Handle reconnection scenarios gracefully
- Implement proper error handling and logging
- Use TypeScript interfaces for type safety
- Follow rate limiting guidelines