Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 52 ยท Advanced Topics

Real-time: WebSockets and Server-Sent Events

Push data to browsers in real time with ASP.NET Core: build a WebSocket echo server, stream Server-Sent Events with TypedResults, and learn when to use SignalR.

Ordinary HTTP is a conversation where the client always speaks first: the browser asks, the server answers, the connection goes quiet. That is perfect for pages and APIs, but awkward for chat messages, live scores, progress bars and notifications, where the server has news at an unpredictable moment. You can poll (ask every few seconds), but polling wastes requests and still feels laggy.

ASP.NET Core offers three ways to push data instead. WebSockets give you a full two-way channel. Server-Sent Events (SSE) give you a simple one-way stream from server to client over plain HTTP. SignalR builds on top of both and adds conveniences. In this lesson you build the first two by hand and learn when each one is the right choice.

Choosing a technique

flowchart TD
    A["Does the client need to send<br/>a continuous stream to the server?"] -->|"yes"| B["WebSockets"]
    A -->|"no, the server mostly pushes"| C["Server-Sent Events"]
    B --> D["Need groups, reconnect, fallbacks,<br/>many clients?"]
    C --> D
    D -->|"yes"| E["SignalR"]
    D -->|"no"| F["Use the raw feature"]

Start with the simplest tool that fits: SSE for one-way pushes, WebSockets for two-way chatter, SignalR when you want the plumbing done for you.

SSE WebSocket
Direction server to client both ways
Transport normal HTTP response that never ends an HTTP upgrade, then its own protocol
Data UTF-8 text events text or binary messages
Browser API EventSource WebSocket
Reconnect automatic, with Last-Event-ID you write it
Works through proxies usually, it is just HTTP needs proxy support for upgrades

WebSockets in ASP.NET Core

A WebSocket starts life as an HTTP request that carries the headers Upgrade: websocket and Connection: Upgrade. If the server agrees, it answers 101 Switching Protocols and both sides keep the TCP connection open and exchange messages in frames instead of requests and responses.

In ASP.NET Core you do three things:

  1. Add the middleware with app.UseWebSockets().
  2. In an endpoint, check context.WebSockets.IsWebSocketRequest.
  3. Call AcceptWebSocketAsync() to complete the handshake and get a WebSocket, then loop on ReceiveAsync and SendAsync until the connection closes.

The endpoint's Task must stay alive for as long as the socket is open: when your handler returns, the connection ends. A message can arrive in several fragments, so you keep reading until EndOfMessage is true. The helper below does that, and the example is a complete echo server plus a client written with ClientWebSocket.

C# A WebSocket echo server and client

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 server loop is the shape of every WebSocket handler: read, react, write, repeat, and leave the loop when a close message arrives. Notice the polite closing handshake: the side that receives a close frame answers with its own, so both ends agree the conversation is over.

WebSockets are long-lived, so treat every connection as a resource. Set limits on message sizes, authenticate before accepting the upgrade (check cookies or a token in the handler, Authentication Concepts), and validate the Origin header if browsers connect, because the browser does not apply CORS rules to WebSockets. UseWebSockets accepts WebSocketOptions such as KeepAliveInterval and AllowedOrigins.

A real server also has to remember its sockets, for example in a ConcurrentDictionary, so it can broadcast to everyone. Keep in mind that a WebSocket allows only one concurrent send and one concurrent receive; two tasks writing at once will throw.

Server-Sent Events

SSE is far simpler. The server sends an ordinary HTTP response with Content-Type: text/event-stream and never finishes it. It writes small text blocks, one event at a time, separated by a blank line:

TEXT
id: 3
event: price
data: {"symbol":"ACME","price":101.5}

Each block can carry data: lines (the payload), an event: name, an id: and a retry: hint. Browsers parse this with the built-in EventSource class, reconnect automatically when the connection drops, and send the last seen id back in a Last-Event-ID header so the server can resume.

.NET 10 added first-class support: TypedResults.ServerSentEvents takes an IAsyncEnumerable<T> and turns every item into an event. Combine it with an async iterator method (yield return) and your endpoint reads like a loop that happens to push to a client. The type SseItem<T> in System.Net.ServerSentEvents lets you set the event type and id for each item, and the same namespace has SseParser for reading a stream on the client.

C# Streaming events with TypedResults.ServerSentEvents

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 half shows exactly what travels over the wire: a text/event-stream body of event: and data: lines. The second half uses SseParser to turn that text back into SseItem<string> values. In a browser, the matching client code is three lines of JavaScript:

JavaScript
const source = new EventSource("/prices");
source.addEventListener("price", (e) => console.log(e.data));
source.onerror = () => console.log("connection lost, the browser will retry");

(That snippet is read-only: a live preview cannot reach your server from a sandboxed frame.) Our example ends the stream after three items; a real feed simply never ends until the client disconnects, which cancels the CancellationToken you passed to the iterator, so your loop stops.

Resuming with Last-Event-ID

Connections drop. When EventSource reconnects it sends the id of the last event it received in a Last-Event-ID request header. If your events have sequential ids, the server can replay what the client missed.

C# Resuming a stream after a reconnect

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 second connection starts at event 3 because the server read Last-Event-ID: 2 and skipped what was already delivered. This is the whole recovery story: durable ids, plus a place to replay from.

SignalR in one page

For larger applications you rarely write raw sockets. SignalR is a library built on top of WebSockets that falls back to SSE or long polling when needed. It adds:

  • Hubs: server classes whose public methods clients can call, and a typed way to call back into clients.
  • Groups and users: Clients.Group("room-1").SendAsync(...) broadcasts to subsets.
  • Automatic reconnect in the client libraries (JavaScript, .NET, Java).
  • Scale-out through a backplane (Redis, Azure SignalR Service) when many servers share clients.

A minimal hub looks like this. It is read-only here, because SignalR is a separate package and framework library that the single-file runner does not use:

C#
public class ChatHub : Hub
{
    public async Task Send(string user, string message) =>
        await Clients.All.SendAsync("message", user, message);
}

// Program.cs
builder.Services.AddSignalR();
app.MapHub<ChatHub>("/chat");

Choose SignalR when you need groups, many connected clients, or automatic fallbacks. Choose raw SSE for one-way feeds like notifications or progress, because it is plain HTTP, works with every proxy and cache rule you already know, and needs no special client library. Choose raw WebSockets when you need binary data or full control of the protocol.

Operating real-time endpoints

  • Idle timeouts: proxies and load balancers close silent connections. Send a periodic comment line or keep-alive event, and set KeepAliveInterval for WebSockets.
  • Each connection costs memory. Thousands of open streams are fine; millions need planning.
  • Disable response buffering and compression for event streams, or messages arrive in clumps.
  • Cancel on disconnect. Always pass HttpContext.RequestAborted into your loops so abandoned connections release their resources.
  • Authenticate first. EventSource cannot set custom headers, so SSE usually relies on cookies; WebSocket clients often pass a token in the query string, which then must not be logged.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which technique fits a live notification feed where only the server sends data?

    SSE is a one-way server-to-client stream over plain HTTP with automatic reconnect, which is exactly what notifications need. WebSockets also work but are more than you need.
  2. 2. What must a WebSocket endpoint handler do for the connection to stay open?

    When the endpoint's Task completes, the connection is torn down. The handler therefore loops on ReceiveAsync until a close message arrives.
  3. 3. How does an SSE client resume after a dropped connection?

    EventSource reconnects automatically and sends the id of the last event it received in the Last-Event-ID request header. The server uses it to replay missed events.
  4. 4. What does SignalR add on top of raw WebSockets?

    SignalR is a higher-level library that chooses a transport (WebSockets, SSE or long polling) and adds hubs, groups, reconnect logic and backplane support for multiple servers.

Summary

  • Use SSE for one-way server pushes, WebSockets for two-way streams and SignalR when you want groups, reconnects and scale-out.
  • WebSockets need app.UseWebSockets(), a check of IsWebSocketRequest, AcceptWebSocketAsync and a receive loop that keeps the handler alive.
  • Messages can be fragmented: read until EndOfMessage, and finish with the closing handshake.
  • TypedResults.ServerSentEvents (.NET 10) streams an IAsyncEnumerable<T> as text/event-stream; SseItem<T> sets event type and id.
  • EventSource reconnects by itself and sends Last-Event-ID, so keep events replayable.
  • Pass RequestAborted into loops, authenticate before streaming and plan for proxy idle timeouts.

Next: OpenAPI, Documentation and API Versioning