Broadcasting
- Introduction
- Complete Example: Two Browser Tabs
- Defining Broadcast Events
- Authorizing Channels
- Broadcasting Events
- Receiving Broadcasts
- Presence Channels
- Notifications
Introduction
Broadcasting pushes server-side events to the browser as they happen, like Laravel's broadcasting with Laravel Echo: an order ships, and the open order page updates itself. DotBlaze broadcasts over a SignalR hub that is part of the web application, so there is nothing else to run, and ships a small Echo-style browser client.
There are three kinds of channels, as in Laravel:
| Channel | Browser name | Who can listen |
|---|---|---|
new Channel("posts") | posts | Anyone. |
new PrivateChannel("orders.1") | private-orders.1 | Logged-in users your authorization callback allows. |
new PresenceChannel("chat.1") | presence-chat.1 | Like private, and every member knows who else is listening. |
Configuration
config/Broadcasting.cs:
public class BroadcastingConfig : ConfigFile
{
public override object Values() => new
{
driver = "local",
connection = "default",
path = "/broadcasting",
};
}path is where the hub is mapped. Browser connections live in the web process: when events are broadcast from a queue worker, or the app runs on several servers, set driver = "redis" to use the Redis backplane. Presence channel members are kept in the default cache store; use redis there too with several servers.
Client Side Installation
Install the SignalR client and copy signalr.min.js into wwwroot/build in your asset build (the sample app does this in npm run build):
npm install @microsoft/signalr
node -e "const fs=require('node:fs');fs.mkdirSync('wwwroot/build',{recursive:true});fs.copyFileSync('node_modules/@microsoft/signalr/dist/browser/signalr.min.js','wwwroot/build/signalr.js')"Then load it and DotBlaze's client in the layout, and create the connection. The login cookie authenticates it:
<script src="~/build/signalr.js"></script>
@Broadcast.Scripts()
<script>
window.Echo ??= new DotBlazeEcho(); // or new DotBlazeEcho({ url: "/broadcasting" })
</script>??= keeps a single connection when live page navigation runs the layout's inline scripts again.
Defining Broadcast Events
Implement IShouldBroadcast on an event and return its channels from BroadcastOn:
public sealed record OrderShipped(Order Order) : IShouldBroadcast
{
public IEnumerable<Channel> BroadcastOn() => [new PrivateChannel($"orders.{Order.Id}")];
}Dispatching the event broadcasts it, after its listeners run:
await Event.Dispatch(new OrderShipped(order));Broadcast Name
Browsers listen for the event's class name (OrderShipped). Override BroadcastAs for another name:
public string BroadcastAs() => "order.shipped";Broadcast Data
By default the event itself is sent, serialized like a JSON response (models follow [Hidden], [Appends], ...). Override BroadcastWith to choose:
public object BroadcastWith() => new { id = Order.Id, status = Order.Status };Broadcast Queue
Broadcasts go through the queue, like Laravel's: the request does not wait for them. With the sync driver they are sent right away. BroadcastQueue picks the queue; implement IShouldBroadcastNow instead to always send right away:
public sealed record PostCreated(Post Post) : IShouldBroadcastNow { ... }Broadcast Conditions
public bool BroadcastWhen() => Order.Total > 100;Authorizing Channels
Private and presence channels need an authorization callback, registered in routes/channels.cs. The first parameter is the logged-in user; parameters in braces follow by name, and a parameter typed as a model is fetched by its key (a missing model refuses the subscription). Return true to allow:
public static class Channels
{
public static void Map()
{
Broadcast.Channel("orders.{order}", (User user, Order order) => user.Id == order.UserId);
Broadcast.Channel("users.{id}", (User user, long id) => user.Id == id);
Broadcast.Channel("teams.{teamId}", async (User user, long teamId) => await user.BelongsToTeam(teamId));
}
}Guests, unknown channels, and callbacks that return false or null are refused: the browser's subscription fails with an error.
Broadcasting Events
Event.Dispatch broadcasts events that implement IShouldBroadcast. To broadcast one without running its listeners, use Broadcast.Send:
await Broadcast.Send(new OrderShipped(order));Only to Others
When the browser that caused an event updates itself already, leave it out with ToOthers(). It uses the X-Socket-ID request header, which live component updates send automatically once the Echo client is connected (send Echo.socketId() yourself from other fetch calls):
await Broadcast.Send(new CommentPosted(comment)).ToOthers();Receiving Broadcasts
Listening for Events
Echo.channel("posts").listen("PostCreated", e => console.log(e.title));
Echo.private(`orders.${orderId}`)
.listen("OrderShipped", e => showShipped(e))
.error(e => console.warn("not allowed", e));With live components, forward the event to them; the sample app refreshes its post list this way (see listening for broadcasts for event data, page-specific private channels, and page navigation):
Echo.channel("posts").listen("PostCreated", e => Live.dispatch("post-created", e));[On("post-created")]
public void Refresh() { }Leaving a Channel
Echo.leave(`orders.${orderId}`); // the public, private, and presence channel of that namePresence Channels
A presence channel's callback returns the member's public data instead of true (return null to refuse):
Broadcast.Channel("online", (User user) => new { id = user.Id, name = user.Name });join subscribes, and tells you who is here, who joins, and who leaves. A user with several tabs open counts once. From the sample app's layout:
<span x-data="{ online: [] }"
x-init="Echo.join('online').here(u => online = u).joining(u => online.push(u)).leaving(u => online = online.filter(x => x.id !== u.id))"
x-text="online.length + ' online'"></span>Presence channels can carry events too: Echo.join("chat.1").listen("NewMessage", ...), with new PresenceChannel("chat.1") in BroadcastOn.
Notifications
Broadcast notifications go to the user's own private group; receive them with Echo.notification(n => ...). The internal notification: group prefix is reserved: clients cannot subscribe to or unsubscribe from it. Notification delivery and automatic membership use this prefix, separate from public channels such as User.1. Custom RouteNotificationFor("broadcast", ...) values also receive the internal prefix; they no longer target public channel subscriptions.
When upgrading, restart all web instances and queue workers together and reconnect existing SignalR clients. Old and new instances use different notification group names.
Complete Example: Two Browser Tabs
Use the authenticated Blog application, the SignalR installation/copy command above, and the template's local broadcasting driver. Add:
// app/Http/Controllers/BroadcastDemoController.cs
using DotBlaze;
using Microsoft.AspNetCore.Mvc;
namespace Blog.Controllers;
public record DocumentationPing : IShouldBroadcastNow
{
public IEnumerable<Channel> BroadcastOn() => [new Channel("documentation")];
public string BroadcastAs() => "documentation.ping";
public object BroadcastWith() => new { message = "Hello from the server." };
}
public class BroadcastDemoController : BaseController
{
public IActionResult Show() => View();
public async Task<IActionResult> Send()
{
await Broadcast.Send(new DocumentationPing());
return NoContent();
}
}Inside Web.Map():
Route.Get<Blog.Controllers.BroadcastDemoController>("/broadcast-demo", c => c.Show)
.Name("broadcast-demo.show").Middleware("auth");
Route.Post<Blog.Controllers.BroadcastDemoController>("/broadcast-demo", c => c.Send)
.Name("broadcast-demo.send").Middleware("auth", "throttle:10,1,broadcast-demo");<!-- resources/views/broadcastdemo/Show.blade.html -->
@extends('layouts.app')
@section('content')
<p id="broadcast-status" role="status">Waiting for an event.</p>
<form id="broadcast-form" method="post" action="{{ Route('broadcast-demo.send') }}">
@csrf
<button type="submit">Send event</button>
</form>
<script src="/build/signalr.js"></script>
{{ Broadcast.Scripts() }}
<script>
const status = document.getElementById("broadcast-status");
const echo = new DotBlazeEcho();
echo.channel("documentation")
.listen("documentation.ping", event => { status.textContent = event.message; })
.error(() => { status.textContent = "Subscription failed."; });
document.getElementById("broadcast-form").addEventListener("submit", async event => {
event.preventDefault();
try {
const response = await fetch(event.target.action, {
method: "POST", body: new FormData(event.target),
headers: { Accept: "application/json" },
});
if (!response.ok) status.textContent = `Request failed: ${response.status}`;
} catch {
status.textContent = "The server could not be reached.";
}
});
</script>
@endsectionRun dotblaze serve, sign in, and open /broadcast-demo in two tabs. After both connections subscribe, sending in either tab changes both paragraphs. This public channel carries only fixed demo text. For private data use PrivateChannel, register the owner callback inside Channels.Map(), and subscribe with echo.private(...). Broadcast.Send sends immediately; queued Event.Dispatch requires a worker and a Redis backplane when that worker is a separate process.