Tutorial 7 of 18

How to Send Messages to Multiple Receivers

Fan out one message to multiple known receiver IDs and manage group membership explicitly in your application.

Pub/Sub Basics

12 min read

Fan out a single message to multiple known receiver IDs in one send() call. DNotifier delivers to each recipient independently — there are no shared channels or subscriptions.

When to Use receiverIds

ScenarioApproach
Group chat (your app manages members)Send to each member's user ID
Notify several dashboard sessionsList admin session IDs
Broadcast to a teamYour backend maintains the member list

The send() Contract

FieldDescription
senderIdMust match the connecting user's userId
receiverIdsArray of target user IDs (mutually exclusive with single receiverId)
dataSame JSON payload sent to every recipient
saveHistoryOptional; default true according to per-recipient rules

Example payload:

{
  "type": "text",
  "text": "Hello everyone"
}

Each recipient receives the same data object in their onMessage handler.

Delivery Semantics

  • Recipients who are online receive the message immediately via onMessage.
  • Recipients who are offline do not get live delivery.
  • With saveHistory: true, each recipient can load history when they reconnect for chat use cases.

JavaScript / TypeScript

Send one payload to several recipients with receiverIds.

Basic Example

import WebSocket from "ws";
import { DNotifier } from "@dnotifier-realtime/dnotifier";

const notifier = new DNotifier({
  appId: process.env.DNOTIFIER_APP_ID,
  secret: process.env.DNOTIFIER_SECRET,
  transport: "ws",
  userId: "user-alice",
  WebSocketImpl: WebSocket,
  onConnected: () => {},
  onMessage: (msg) => console.log(msg.payload.toJSON()),
  onDisconnected: () => {},
});

await notifier.connect();

await notifier.send({
  senderId: "user-alice",
  receiverIds: ["user-bob", "user-carol", "user-dave"],
  data: {
    type: "text",
    text: "Hello everyone",
  },
});

Team Notification Pattern

const teamMemberIds = [
  "employee-101",
  "employee-102",
  "employee-103",
];

await notifier.send({
  senderId: "svc-notifications",
  receiverIds: teamMemberIds,
  data: {
    type: "notification",
    title: "Deploy complete",
    body: "v2.4.0 is live in production.",
  },
  saveHistory: false,
});

Dynamic Member List

async function broadcastToRoom(roomId, payload) {
  const members = await loadRoomMembersFromYourDb(roomId);
  const receiverIds = members.map((member) => member.userId);

  await notifier.send({
    senderId: currentUserId,
    receiverIds,
    data: payload,
  });
}

Your app owns room membership, moderation, and access control.

sendBinary With Multiple Receivers

notifier.sendBinary({
  senderId: "user-alice",
  receiverIds: ["user-bob", "user-carol"],
  buffer: new Uint8Array([0x00, 0x01, 0x02]),
  type: "binary",
});

Troubleshooting

IssueCheck
Only some recipients receiveOffline users won't get live delivery
receiverId or receiverIds requiredPass receiverIds as a non-empty array
Wrong recipientsVerify your member list matches DNotifier userId values

Dart / Flutter

Send one payload to several recipients with receiverIds.

Basic Example

import 'package:dnotifier/dnotifier.dart';

Future<void> main() async {
  final notifier = DNotifier(
    appId: 'your-app-id',
    secret: 'your-app-secret',
    transport: 'ws',
    userId: 'user-alice',
    onConnected: () {},
    onMessage: (msg) => print(msg.payload.toJSON()),
  );

  await notifier.connect();

  await notifier.send(
    senderId: 'user-alice',
    receiverIds: ['user-bob', 'user-carol', 'user-dave'],
    data: {
      'type': 'text',
      'text': 'Hello everyone',
    },
  );
}

Team Notification Pattern

const teamMemberIds = [
  'employee-101',
  'employee-102',
  'employee-103',
];

await notifier.send(
  senderId: 'svc-notifications',
  receiverIds: teamMemberIds,
  data: {
    'type': 'notification',
    'title': 'Deploy complete',
    'body': 'v2.4.0 is live in production.',
  },
  saveHistory: false,
);

Dynamic Member List

Future<void> broadcastToRoom(
  String roomId,
  Map<String, dynamic> payload,
) async {
  final members = await loadRoomMembersFromYourDb(roomId);
  final receiverIds = members.map((member) => member.userId).toList();

  await notifier.send(
    senderId: currentUserId,
    receiverIds: receiverIds,
    data: payload,
  );
}

Your app owns room membership, moderation, and access control.

sendBinary With Multiple Receivers

notifier.sendBinary(
  senderId: 'user-alice',
  receiverIds: ['user-bob', 'user-carol'],
  buffer: [0x00, 0x01, 0x02],
);

Troubleshooting

IssueCheck
Only some recipients receiveOffline users won't get live delivery
ArgumentError: receiverId or receiverIds requiredPass non-empty receiverIds
Wrong recipientsVerify the member list matches DNotifier userId values

Python

Send one payload to several recipients with receiver_ids.

Basic Example

import asyncio
from dnotifier import DNotifier

async def main():
    notifier = DNotifier(
        app_id="your-app-id",
        secret="your-app-secret",
        transport="ws",
        user_id="user-alice",
        on_connected=lambda: None,
        on_message=lambda msg: print(msg.payload.to_json()),
    )

    await notifier.connect()

    await notifier.send(
        sender_id="user-alice",
        receiver_ids=["user-bob", "user-carol", "user-dave"],
        data={"type": "text", "text": "Hello everyone"},
    )

asyncio.run(main())

Team Notification Pattern

TEAM_MEMBER_IDS = [
    "employee-101",
    "employee-102",
    "employee-103",
]

await notifier.send(
    sender_id="svc-notifications",
    receiver_ids=TEAM_MEMBER_IDS,
    data={
        "type": "notification",
        "title": "Deploy complete",
        "body": "v2.4.0 is live in production.",
    },
    save_history=False,
)

Dynamic Member List

async def broadcast_to_room(notifier, room_id: str, payload: dict):
    members = await load_room_members_from_your_db(room_id)
    receiver_ids = [member.user_id for member in members]

    await notifier.send(
        sender_id=current_user_id,
        receiver_ids=receiver_ids,
        data=payload,
    )

Your app owns room membership, moderation, and access control.

send_binary With Multiple Receivers

await notifier.send_binary(
    sender_id="user-alice",
    receiver_ids=["user-bob", "user-carol"],
    buffer=bytes([0x00, 0x01, 0x02]),
)

Troubleshooting

IssueCheck
Only some recipients receiveOffline users won't get live delivery
ValueError: receiver_id or receiver_ids requiredPass non-empty receiver_ids
Wrong recipientsVerify the member list matches DNotifier user_id values