Broadcast Messages

This guide shows you how to broadcast messages to multiple WebSocket clients.

Basic Broadcasting

Broadcast to all connected clients:

class NotificationChannel < Azu::Channel
  PATH = "/notifications"

  CONNECTIONS = [] of HTTP::WebSocket

  def on_connect
    CONNECTIONS << socket
  end

  def on_close(code, reason)
    CONNECTIONS.delete(socket)
  end

  def self.broadcast(message : String)
    CONNECTIONS.each do |ws|
      ws.send(message)
    end
  end
end

Trigger broadcast from anywhere:

Broadcast to Others

Broadcast to all except the sender:

Room-based Broadcasting

Broadcast to specific rooms:

User-targeted Broadcasting

Send to specific users:

Broadcast with Filtering

Filter recipients based on criteria:

Async Broadcasting

Use fibers for non-blocking broadcasts:

Broadcast from Background Jobs

Trigger broadcasts from background processes:

Rate-limited Broadcasting

Prevent broadcast flooding:

Batched Broadcasting

Batch multiple messages:

See Also

Last updated

Was this helpful?