Messaging API

Real-time messaging system with WebSocket support for game events, input handling, and peer communication

Quick Start

Get started with Playcast messaging in your application:

import {
  PlaycastMessage,
  PlaycastMessageTarget,
  validators,
  generators
} from '@playcastdotio/Messaging';

// Create a message
const message = generators.gamepad.createGamepadEvent({
  userId: 'user123',
  buttonPressed: 'A',
  timestamp: Date.now()
});

// Validate message
const isValid = validators.validatePlaycastMessage(message);

// Send via WebSocket or other transport
if (isValid) {
  websocket.send(JSON.stringify(message));
}

Playcast Messages

Core message format for all Playcast communication. All messages follow a consistent structure with headers, body, and timing information.

type PlaycastMessage<T extends PlaycastMessageTarget>

Message Structure

Property Type Description
signature string Message signature for validation
header PlaycastMessageHeader Message metadata and routing information
body MessageBody Message payload, timings, stats, and echo flag

Message Header

type PlaycastMessageHeader = {
  tag: string;                    // Unique message identifier
  source: PlaycastMessageSource; // 'player' | 'host' | 'playjector'
  schemaVersion: 5;               // Message schema version
  timestamp: number;              // Unix timestamp
  user: PlaycastUser;             // User information
  target: string;                 // Message target (e.g., 'gamepad')
  action: string;                 // Action to perform
  isReply: boolean;               // Whether this is a reply
};

Message Types

PlaycastCameraMessages Playcast

Camera control and configuration messages for video capture management.

PlaycastGamepadMessages Playcast

Gamepad input events including button presses, analog stick movements, and triggers.

PlaycastKeyboardMessages Playcast

Keyboard input events for key presses, releases, and modifier states.

PlaycastMouseMessages Playcast

Mouse input events including movement, clicks, and scroll wheel actions.

PlaycastStreamMessages Playcast

Stream management messages for quality control, encoding settings, and stream state.

WebSocket Messages

WebSocket-specific message types for real-time communication between client and server.

Note: WebSocket messages are separate from Playcast messages and use their own type system for server communication.

Message Types

AuthMessage WebSocket

Authentication and authorization messages for session management.

ConnectionMessage WebSocket

Connection lifecycle messages for establishing and maintaining WebSocket connections.

PeerMessage WebSocket

Peer-to-peer signaling messages for WebRTC connection establishment.

PresenceMessage WebSocket

User presence and status updates for lobby and session management.

Usage Example

import {
  WebsocketMessage,
  WebsocketMessageType,
  generateAuthMessage
} from '@playcastdotio/Messaging';

// Create an auth message
const authMessage = generateAuthMessage(
  WebsocketMessageType.AUTH_REQUEST,
  {
    token: 'jwt_token_here',
    machineId: 'machine_123'
  }
);

// Send via WebSocket
websocket.send(JSON.stringify(authMessage));

Message Validators

Validate message structure and content before processing.

validatePlaycastMessage(message: string | object): PlaycastMessage | null

Parameters

Parameter Type Required Description
message string | object Required Message to validate (JSON string or object)

Returns

Returns a validated PlaycastMessage object if valid, or null if validation fails.

import { validators } from '@playcastdotio/Messaging';

// Validate a message string
const messageString = '{"signature":"...","header":{...},"body":{...}}';
const validatedMessage = validators.validatePlaycastMessage(messageString);

if (validatedMessage) {
  console.log('Message is valid:', validatedMessage);
  processMessage(validatedMessage);
} else {
  console.error('Invalid message format');
}
Important: Always validate messages from external sources before processing to ensure data integrity and security.

Message Generators

Helper functions to create properly formatted messages for different input types and system events.

Available Generators

  • camera - Camera control and configuration messages
  • encoder - Video encoding and compression settings
  • gamepad - Controller input events
  • host - Host system control messages
  • hub - Hub coordination and routing messages
  • input - Generic input handling messages
  • keyboard - Keyboard input events
  • mouse - Mouse input events
  • player - Player state and control messages
  • stream - Stream quality and management messages

Gamepad Generator Example

import { generators } from '@playcastdotio/Messaging';

// Generate gamepad button press event
const buttonPress = generators.gamepad.createButtonEvent({
  userId: 'user123',
  button: 'A',
  pressed: true,
  timestamp: Date.now()
});

// Generate analog stick movement
const stickMovement = generators.gamepad.createStickEvent({
  userId: 'user123',
  stick: 'left',
  x: 0.75,
  y: -0.3,
  timestamp: Date.now()
});

Mouse Generator Example

import { generators } from '@playcastdotio/Messaging';

// Generate mouse movement event
const mouseMove = generators.mouse.createMoveEvent({
  userId: 'user123',
  x: 100,
  y: 200,
  deltaX: 5,
  deltaY: -3,
  timestamp: Date.now()
});

// Generate mouse click event
const mouseClick = generators.mouse.createClickEvent({
  userId: 'user123',
  button: 'left',
  pressed: true,
  x: 100,
  y: 200,
  timestamp: Date.now()
});

Timing and Performance

Playcast messages include timing information to track message flow and performance across the system.

type PlaycastTimingEntry = { app: PlaycastMessageSource; timestamp: number; description: string; metadata: Record<string, string>; }

Adding Timing Information

// Messages automatically include timing information
const message = generators.gamepad.createButtonEvent({
  userId: 'user123',
  button: 'A',
  pressed: true,
  timestamp: Date.now()
});

// Add custom timing entry
message.body.timings.push({
  app: 'player',
  timestamp: Date.now(),
  description: 'Message processed by input handler',
  metadata: {
    handler: 'GamepadInputHandler',
    processingTime: '2.3ms'
  }
});