demonstrateServerBroadcast function

Future<void> demonstrateServerBroadcast(
  1. StompService service,
  2. StompClient client
)

Implementation

Future<void> demonstrateServerBroadcast(StompService service, StompClient client) async {
  print('\n📡 Example 4: Server-side Broadcasting');

  // Subscribe to a broadcast destination
  final subscription = await client.subscribe(
    destination: '/broadcast/all',
    ackMode: StompAckMode.auto,
  );

  print('✅ Subscribed to broadcast destination');

  // Set up message listener
  final messageCompleter = Completer<void>();
  late StreamSubscription messageSubscription;

  messageSubscription = subscription.messages.listen((message) {
    print('📻 Received broadcast message: ${message.body}');
    messageCompleter.complete();
  });

  // Server broadcasts a message
  await service.server?.sendToDestination(
    destination: '/broadcast/all',
    body: 'System announcement: Server is running smoothly!',
    contentType: 'text/plain',
  );

  // Wait for the broadcast message
  await messageCompleter.future.timeout(const Duration(seconds: 5));
  await messageSubscription.cancel();

  print('✅ Broadcast example completed');
}