Skip to main content

Send Message to All Players

Send messages to all players in a Standard Room simultaneously using the standardmessagetoall method. This is ideal for game state updates, chat messages, and announcements that everyone needs to receive.

Method Signature

MoitribeSDK(gameId, 'standardmessagetoall', params, callback)

Parameters

ParameterTypeRequiredDescription
messageDataArrayBufferYesMessage content as binary data
isReliablebooleanNoWhether message must be delivered reliably (default: true)

Examples

Send Game State Update

Broadcast the current game state to all players:

// Create game state object
const gameState = {
type: 'gameState',
turn: 5,
currentPlayer: 'player123',
board: [
['X', 'O', ''],
['', 'X', 'O'],
['O', '', 'X']
],
scores: { player123: 10, player456: 8 }
};

// Convert to ArrayBuffer
const encoder = new TextEncoder();
const jsonString = JSON.stringify(gameState);
const messageData = encoder.encode(jsonString).buffer;

// Send to all players
MoitribeSDK('my-game-id', 'standardmessagetoall', {
messageData: messageData,
isReliable: true // Game state must be reliable
}, (result) => {
if (result.success) {
console.log('Game state broadcasted to all players');
} else {
console.error('Failed to send game state:', result.msg);
}
});

Send Chat Message

Broadcast a chat message to all players:

function sendChatMessage(message) {
const chatData = {
type: 'chat',
message: message,
sender: 'player123',
timestamp: Date.now()
};

const encoder = new TextEncoder();
const messageData = encoder.encode(JSON.stringify(chatData)).buffer;

MoitribeSDK('my-game-id', 'standardmessagetoall', {
messageData: messageData,
isReliable: true // Chat messages should be reliable
}, (result) => {
if (result.success) {
console.log('Chat message sent:', message);
displayMessageInChat(message, 'You');
} else {
console.error('Failed to send chat message');
showErrorMessage('Message failed to send');
}
});
}

// Usage
sendChatMessage('Good move!');
sendChatMessage('Anyone up for another round?');

Send Real-Time Position Update

Send fast, unreliable position updates for real-time games:

function sendPositionUpdate(x, y, velocity) {
const positionData = {
type: 'position',
x: x,
y: y,
vx: velocity.x,
vy: velocity.y,
timestamp: Date.now()
};

const encoder = new TextEncoder();
const messageData = encoder.encode(JSON.stringify(positionData)).buffer;

// Send as unreliable for faster delivery
MoitribeSDK('my-game-id', 'standardmessagetoall', {
messageData: messageData,
isReliable: false // Position updates can be unreliable for speed
}, (result) => {
if (result.success) {
console.log('Position update sent');
} else {
console.error('Failed to send position update');
}
});
}

// Send updates frequently (60 FPS)
setInterval(() => {
const playerPos = getPlayerPosition();
sendPositionUpdate(playerPos.x, playerPos.y, playerPos.velocity);
}, 16); // ~60 FPS

Send Game Event

Broadcast important game events to all players:

function sendGameEvent(eventType, data) {
const eventData = {
type: 'gameEvent',
event: eventType,
data: data,
timestamp: Date.now()
};

const encoder = new TextEncoder();
const messageData = encoder.encode(JSON.stringify(eventData)).buffer;

MoitribeSDK('my-game-id', 'standardmessagetoall', {
messageData: messageData,
isReliable: true // Game events must be reliable
}, (result) => {
if (result.success) {
console.log(`Game event sent: ${eventType}`);
} else {
console.error(`Failed to send game event: ${eventType}`);
}
});
}

// Example game events
sendGameEvent('roundStart', { round: 3 });
sendGameEvent('powerUpSpawned', { type: 'speed', position: { x: 100, y: 200 } });
sendGameEvent('playerEliminated', { playerId: 'player456', reason: 'timeout' });
sendGameEvent('gameOver', { winner: 'player123', finalScores: [100, 85, 72] });

Response Format

The callback receives a response object:

{
success: boolean;
msg?: string; // Error message if failed
}

Message Data Format

ArrayBuffer Conversion

All messages must be sent as ArrayBuffer. Here are common conversion methods:

// String to ArrayBuffer
const encoder = new TextEncoder();
const messageData = encoder.encode(stringMessage).buffer;

// Object to ArrayBuffer
const jsonString = JSON.stringify(object);
const messageData = encoder.encode(jsonString).buffer;

// Binary data to ArrayBuffer
const binaryData = new Uint8Array([1, 2, 3, 4]);
const messageData = binaryData.buffer;

Message Structure

Include a type field for message identification:

const message = {
type: 'messageType', // Required for message routing
// ... other data
};

Reliable vs Unreliable Messages

Reliable Messages (isReliable: true)

  • Use for: Game state, chat, important events
  • Guaranteed delivery to all players
  • Slower but more reliable
  • Order is preserved

Unreliable Messages (isReputable: false)

  • Use for: Position updates, animations, frequent data
  • Faster delivery but not guaranteed
  • May be dropped if network is congested
  • Perfect for real-time data

Error Handling

Common errors and solutions:

ErrorCauseSolution
Message is requiredEmpty message dataEnsure messageData is not null/undefined
Invalid message formatNon-ArrayBuffer dataConvert data to ArrayBuffer before sending
Not in roomPlayer not connected to roomJoin room before sending messages
Room disconnectedNetwork connection lostHandle reconnection before sending
warning

Always convert your message data to ArrayBuffer before sending. The SDK will reject non-ArrayBuffer data.

Best Practices

Message Size

  • Keep messages small (under 1KB when possible)
  • Use efficient data structures
  • Compress large data if needed

Message Frequency

  • Reliable messages: Use sparingly (game state changes, important events)
  • Unreliable messages: Can send frequently (position updates, animations)

Message Structure

  • Always include a type field for message routing
  • Use consistent naming conventions
  • Include timestamps for time-sensitive data

Error Handling

  • Always check the callback result
  • Implement retry logic for important messages
  • Show user feedback for failed sends

Next Steps