Send Message to All Players
Send messages to all players currently in the endless room. This is perfect for game state updates, chat messages, and global events that all players need to receive.
Method
MoitribeSDK('game-id', 'endlessmessagetoall', params, callback)
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
messageData | ArrayBuffer | Yes | Message data to send |
isReliable | boolean | No | Whether message must be delivered (default: true) |
Response Format
{
success: boolean;
msg?: string;
}
Examples
JavaScript Example
// Send a simple text message to all players
function sendChatMessage(text) {
const encoder = new TextEncoder();
const messageData = encoder.encode(text);
MoitribeSDK('my-game', 'endlessmessagetoall', {
messageData: messageData.buffer,
isReliable: true
}, (result) => {
if (result.success) {
console.log('Chat message sent to all players');
} else {
console.error('Failed to send message:', result.msg);
}
});
}
// Send game state update
function sendGameStateUpdate(gameState) {
const messageData = createGameUpdateBuffer(gameState);
MoitribeSDK('my-game', 'endlessmessagetoall', {
messageData: messageData,
isReliable: true // Game state should be reliable
}, (result) => {
console.log('Game state update sent:', result.success);
});
}
// Send position update (unreliable for performance)
function sendPositionUpdate(x, y, z) {
const buffer = new ArrayBuffer(12); // 3 floats (4 bytes each)
const view = new DataView(buffer);
view.setFloat32(0, x, true);
view.setFloat32(4, y, true);
view.setFloat32(8, z, true);
MoitribeSDK('my-game', 'endlessmessagetoall', {
messageData: buffer,
isReliable: false // Position updates can be unreliable
}, (result) => {
// Don't log for unreliable messages to reduce console spam
});
}
TypeScript Example
import MoitribeSDK from '@veniso/moitribe-js';
// Send a structured game event
interface GameEvent {
type: 'player_scored' | 'game_paused' | 'round_started';
playerId: string;
data?: any;
timestamp: number;
}
function sendGameEvent(event: GameEvent): void {
const messageData = encodeGameEvent(event);
MoitribeSDK('my-game', 'endlessmessagetoall', {
messageData: messageData,
isReliable: true
}, (result: any) => {
if (result.success) {
console.log(`Game event sent: ${event.type}`);
} else {
console.error('Failed to send game event:', result.msg);
}
});
}
// Helper function to encode game events
function encodeGameEvent(event: GameEvent): ArrayBuffer {
const json = JSON.stringify(event);
const encoder = new TextEncoder();
return encoder.encode(json).buffer;
}
// Usage examples
sendGameEvent({
type: 'player_scored',
playerId: 'player123',
data: { points: 100, multiplier: 2 },
timestamp: Date.now()
});
Message Types
Reliable Messages
Use reliable messages for critical game data:
// Critical game state
function sendCriticalUpdate(data) {
MoitribeSDK('my-game', 'endlessmessagetoall', {
messageData: encodeData(data),
isReliable: true // Guaranteed delivery
});
}
// Examples of reliable messages:
// - Game score updates
// - Player elimination
// - Round results
// - Game state changes
Unreliable Messages
Use unreliable messages for frequent, non-critical updates:
// Frequent position updates
function sendPosition(x, y) {
const buffer = new ArrayBuffer(8);
const view = new DataView(buffer);
view.setFloat32(0, x, true);
view.setFloat32(4, y, true);
MoitribeSDK('my-game', 'endlessmessagetoall', {
messageData: buffer,
isReliable: false // Better performance
});
}
// Examples of unreliable messages:
// - Position updates
// - Animation states
// - Temporary effects
// - Input states
Data Encoding
Text Messages
function sendTextMessage(text) {
const encoder = new TextEncoder();
const messageData = encoder.encode(text);
MoitribeSDK('my-game', 'endlessmessagetoall', {
messageData: messageData.buffer,
isReliable: true
});
}
JSON Data
function sendJsonObject(data) {
const jsonString = JSON.stringify(data);
const encoder = new TextEncoder();
const messageData = encoder.encode(jsonString);
MoitribeSDK('my-game', 'endlessmessagetoall', {
messageData: messageData.buffer,
isReliable: true
});
}
Binary Data
function sendBinaryMessage(data) {
// Create a structured binary message
const buffer = new ArrayBuffer(16);
const view = new DataView(buffer);
view.setUint8(0, data.type); // Message type (1 byte)
view.setUint32(1, data.playerId); // Player ID (4 bytes)
view.setFloat32(5, data.x); // X position (4 bytes)
view.setFloat32(9, data.y); // Y position (4 bytes)
view.setUint16(13, data.flags); // Flags (2 bytes)
MoitribeSDK('my-game', 'endlessmessagetoall', {
messageData: buffer,
isReliable: false
});
}
Performance Considerations
Message Frequency
// Throttle position updates to avoid flooding
let lastPositionUpdate = 0;
const POSITION_UPDATE_INTERVAL = 50; // 50ms
function sendThrottledPosition(x, y) {
const now = Date.now();
if (now - lastPositionUpdate >= POSITION_UPDATE_INTERVAL) {
sendPosition(x, y);
lastPositionUpdate = now;
}
}
Message Size
// Keep messages small for better performance
function sendCompactUpdate(data) {
// Use bit flags instead of booleans
const flags =
(data.isJumping ? 1 : 0) |
(data.isRunning ? 2 : 0) |
(data.isAttacking ? 4 : 0);
const buffer = new ArrayBuffer(9);
const view = new DataView(buffer);
view.setUint8(0, flags);
view.setFloat32(1, data.x);
view.setFloat32(5, data.y);
MoitribeSDK('my-game', 'endlessmessagetoall', {
messageData: buffer,
isReliable: false
});
}
Error Handling
function sendMessageWithErrorHandling(messageData, isReliable = true) {
MoitribeSDK('my-game', 'endlessmessagetoall', {
messageData,
isReliable
}, (result) => {
if (!result.success) {
console.error('Message send failed:', result.msg);
// Handle specific errors
if (result.msg?.includes('not in room')) {
showReconnectDialog();
} else if (result.msg?.includes('message too large')) {
console.error('Message exceeds size limit');
}
}
});
}
Best Practices
Message Batching
// Batch multiple updates into one message
function batchUpdates(updates) {
const batchData = {
type: 'batch',
timestamp: Date.now(),
updates: updates
};
sendJsonObject(batchData);
}
// Usage
batchUpdates([
{ type: 'position', x: 100, y: 200 },
{ type: 'health', value: 85 },
{ type: 'score', points: 1500 }
]);
Message Prioritization
// Send important messages immediately
function sendUrgentMessage(data) {
MoitribeSDK('my-game', 'endlessmessagetoall', {
messageData: encodeData(data),
isReliable: true
});
}
// Queue less important messages
const messageQueue = [];
function queueMessage(data) {
messageQueue.push(data);
}
function flushMessageQueue() {
if (messageQueue.length > 0) {
const batch = {
type: 'queued_messages',
messages: messageQueue.splice(0) // Clear queue
};
sendJsonObject(batch);
}
}
// Flush queue periodically
setInterval(flushMessageQueue, 100);
Next Steps
- Send to Specific Player - Send targeted messages
- Send to Server - Communicate with game server
- Receive Messages - Handle incoming messages
- Message Reliability - Understand delivery guarantees
Performance Tip
Use unreliable messages for high-frequency updates like positions and animations. Use reliable messages for critical game state changes.