Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 52 ยท Projects

Project: Real-time Chat with SSE and WebSockets

Build a multi-room chat in ASP.NET Core: broadcast with Channel<T>, a Server-Sent Events stream with resume, and a two-way WebSocket endpoint.

Chat is the classic real-time application. A message posted by one person must appear on everybody else's screen within moments, without anyone pressing refresh. That needs three pieces: a way for clients to send messages, a way for the server to push them out, and a central place that remembers who is listening.

In this project you build all three with plain ASP.NET Core and no extra packages. Messages enter through a normal POST, or through a WebSocket. Listeners receive them through Server-Sent Events (one-way streaming over ordinary HTTP) or through the same WebSocket (two-way). Inside, a small hub uses System.Threading.Channels to broadcast to every subscriber of a room. The whole demo runs in one program: the server starts on loopback, and the client side uses HttpClient and ClientWebSocket.

If you want the protocol background first, read Real-time: WebSockets and Server-Sent Events and Background Services. This lesson focuses on putting them into one design.

The architecture

flowchart LR
    P1["POST /rooms/{room}/messages"] --> H
    W1["WebSocket client sends"] --> H
    H["ChatHub<br/>Room.Publish"] --> C1["Channel for subscriber 1"]
    H --> C2["Channel for subscriber 2"]
    H --> C3["Channel for subscriber 3"]
    C1 --> S1["SSE stream<br/>GET /rooms/{room}/events"]
    C2 --> S2["SSE stream"]
    C3 --> W2["WebSocket send loop<br/>/ws/{room}"]

Every subscriber gets its own channel, so a slow listener cannot block the sender or the other listeners.

The key design choice is one channel per subscriber. A channel is an asynchronous queue: a producer writes, a consumer awaits and reads. When a message is published, the room writes it into every subscriber's queue and returns immediately. Each listener drains its own queue at its own pace. If one phone is on a bad connection, only its queue grows; nobody else waits.

Step 1: the hub

The hub keeps rooms in a dictionary. Each room stores its recent history (so late joiners and reconnecting clients can catch up), a counter for message ids, and the subscriber channels. All of that state is guarded by one lock, which is short and never held across an await.

Two details deserve attention:

  • Bounded channels with DropOldest. An unbounded queue for a client that never reads is a memory leak waiting to happen. A bounded queue of 100 that drops its oldest entry when full limits memory per subscriber. For chat, losing the oldest unread message of a stalled client is acceptable; for other systems you might disconnect the slow client instead (FullMode = Wait plus a timeout).
  • Replay and subscribe atomically. Subscribe copies the history into the new channel and registers it inside the same lock. If these were separate steps, a message could slip in between and be missed or delivered twice.

Try the hub with no web server at all, which is also how you would unit test it:

C# Step 1: rooms, channels and replay

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first subscriber receives all three messages, the reconnecting one only message 2 and 3, and the live-only subscriber only the message published after it joined. The slow subscriber, whose queue holds three items, ends up with the latest three of six messages: the oldest were dropped, memory stayed bounded, and Publish never blocked.

Disposing a subscription removes it from the room and completes its channel. Completing is what makes await foreach (... in reader.ReadAllAsync()) loops end cleanly, which matters in the next step.

Step 2: the HTTP surface

Three endpoints expose the hub.

POST /rooms/{room}/messages validates and publishes. Plain HTTP is a fine way to send even when listeners use a stream; it works from any client, passes through proxies easily and can be authenticated like any other endpoint.

GET /rooms/{room}/events is the Server-Sent Events stream. SSE is just a long-lived HTTP response with the content type text/event-stream, where each event is a few lines of text ending with a blank line. Browsers consume it with the built-in EventSource class, which reconnects automatically and sends the Last-Event-ID header carrying the id of the last event it saw. Our endpoint uses that header as the afterId for Subscribe, so a reconnecting browser silently catches up on what it missed. Since .NET 10, TypedResults.ServerSentEvents turns an IAsyncEnumerable<SseItem<T>> into such a response.

GET /ws/{room} upgrades to a WebSocket: a two-way channel that stays open. The handler runs a send loop (draining the subscription to the socket) next to a receive loop (publishing what the client sends). Only the send loop writes to the socket, which respects the rule that a WebSocket allows one concurrent sender and one concurrent receiver.

When should you pick which? SSE is simpler (plain HTTP, automatic reconnect, works through most proxies) and enough whenever data flows server to client, with ordinary requests going the other way. WebSockets are worth their extra complexity for high-frequency two-way traffic such as games or collaborative editing. For rooms, presence, groups and fallbacks at scale, SignalR builds all of this for you; knowing the pieces underneath makes it much easier to use.

Step 3: the complete chat

The program below contains the hub from step 1, the three endpoints and a script that plays several clients: an SSE listener in general, an HTTP sender, a WebSocket participant, a listener in another room, and finally a reconnecting SSE client that resumes from Last-Event-ID.

C# The chat server and its clients

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Read the three outputs in order.

The SSE wire format is plain text. Each event has an event: line (the type, which EventSource can listen for by name), a data: line (our message as JSON) and an id: line, followed by an empty line that ends the event. Alice received the HTTP-posted message, Bob's WebSocket message and the last one, in order, and not Carol's message from the random room: rooms isolate subscribers.

Bob's WebSocket received the same broadcast as JSON text frames: his own message came back to him (the server broadcasts to everyone in the room, sender included), then Alice's last message. His send and his receive were running independently on one connection.

The resume at the end. A client that connects with Last-Event-ID: 1 is replayed messages 2 and 3 from the room history before it receives live traffic. With EventSource in a browser you get this for free: it stores the last id: and sends it on reconnect.

Finally the subscriber count returns to zero: when clients disconnected, RequestAborted ended the SSE loops and closing the socket ended the WebSocket handler, and the using blocks removed every subscription. Leaked subscribers are the number one bug in hand-written real-time code, so make cleanup a habit and watch that gauge (see Observability in Production).

Going to production

  • Scale-out. This hub lives in one process. With two servers, a message posted to server A never reaches listeners on server B. The fix is a shared backplane: Redis pub/sub, a message queue, or SignalR with its Redis or Azure backplane. The room abstraction stays the same; Publish goes through the backplane.
  • Authentication. Browsers cannot set headers on EventSource or WebSocket connections, so use cookies, or pass a short-lived token in the query string and validate it when the connection opens (Cookie and JWT Bearer Authentication). Never trust the user field from the client as this demo does; take it from the authenticated principal, as in Project: Notes API with Authentication.
  • Origin checks. WebSockets are not covered by CORS. Check the Origin header on upgrade (or configure WebSocketOptions.AllowedOrigins) to prevent other sites from opening sockets with your users' cookies.
  • Proxies and timeouts. Reverse proxies close idle connections. Send an SSE comment line or WebSocket ping every 15 to 30 seconds (KeepAliveInterval for WebSockets), disable response buffering for the stream, and configure the proxy for the Upgrade header (Deployment).
  • Limits. Cap message size, rate limit senders and cap the number of connections per user.
  • Persistence. History in memory disappears on restart. Save messages to a database and have Subscribe read from it for replays.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does each subscriber get its own channel?

    Publishing writes into each subscriber's queue and returns. Each consumer reads at its own speed.
  2. 2. What does BoundedChannelFullMode.DropOldest do for a stalled client?

    The queue never grows past its capacity. The cost is that a stalled client may lose old unread messages.
  3. 3. How does a browser's EventSource resume after a dropped connection without missing events?

    EventSource reconnects automatically and sends Last-Event-ID, which the server can use to replay missed events.
  4. 4. Why must only one piece of code write to a WebSocket at a time?

    A WebSocket supports one outstanding send and one outstanding receive at a time. A dedicated send loop satisfies that.
  5. 5. When is SSE a better fit than WebSockets?

    SSE is simpler, works over ordinary HTTP and reconnects by itself. WebSockets pay off for high-frequency two-way communication.

Summary

  • A hub with one Channel<T> per subscriber broadcasts without letting slow clients block anyone; bound the queues and drop the oldest.
  • Replay history and register a subscriber in one locked step, so no message is lost or duplicated.
  • SSE (TypedResults.ServerSentEvents, text/event-stream, Last-Event-ID) is the simple one-way stream; WebSockets give a two-way connection with a send loop and a receive loop.
  • Always unsubscribe on disconnect and watch the subscriber count for leaks.
  • In production add a backplane for several servers, authenticate connections, check origins, send keep-alives and limit sizes and rates.

Next: Project: Blog API with Pagination and Caching