Skip to Content
DocsGame ServerReal-time Messaging

Real-time Messaging

This guide explains how to implement real-time messaging in Agent8 using both global and room-scoped communication channels. Send targeted messages to individual users or broadcast to entire groups with guaranteed delivery.

Message types should be unique strings that identify the message format. Use consistent types for similar messages across your application.

Server API

Global Messaging

  • $global.broadcastToAll(type: string, message: any)
    Broadcasts a message to all connected users globally.
  • $global.sendMessageToUser(type: string, account: string, message: any)
    Sends a direct message to a specific user account globally.

Room Messaging

  • $room.broadcastToRoom(type: string, message: any)
    Broadcasts a message to all users in the current room.
  • $room.sendMessageToUser(type: string, account: string, message: any)
    Sends a direct message to a specific user within the current room.
server.js
class Server { // Global announcement example async sendGlobalAnnouncement(message) { await $global.broadcastToAll("GLOBAL_ANNOUNCEMENT", { text: message, timestamp: Date.now(), }); } // Room message example async sendRoomUpdate(roomId, update) { await $room.broadcastToRoom("ROOM_UPDATE", { roomId, update, timestamp: Date.now(), }); } }

Client API

Message Subscription

const { server } = useGameServer(); server.onGlobalMessage("GLOBAL_ANNOUNCEMENT", (message) => { console.log("Global announcement:", message); }); server.onRoomMessage(roomId, "ROOM_UPDATE", (message) => { console.log("Room update:", message); });

Example: Real-time Chat System

server.js
class Server { // Send global chat message async sendGlobalChat(message) { const account = await $global.getMyAccount(); await $global.broadcastToAll("GLOBAL_CHAT", { sender: account, text: message, timestamp: Date.now(), }); } // Send room chat message async sendRoomChat(roomId, message) { const account = await $global.getMyAccount(); await $room.broadcastToRoom("ROOM_CHAT", { sender: account, text: message, timestamp: Date.now(), }); } }
Last updated on