Skip to content
Tutorials Center
My learning

Topics

Lesson 142 of 182 ยท ASP.NET Core

SignalR, WebSockets and gRPC

Learn real-time communication in ASP.NET Core - long polling, Server-Sent Events, WebSockets, SignalR hubs on the wire and gRPC streaming - with runnable C# loopback demos and guidance on choosing.

Classic HTTP is a question and an answer: the browser asks, the server replies, the conversation ends. That is perfect for pages and APIs, and awkward for anything where the server has news: a chat message, a stock price, a build log scrolling by, a notification, a multiplayer move. Real-time features need a way for the server to push data to the client the moment it exists.

ASP.NET Core supports the whole ladder of techniques, from simple tricks on plain HTTP to high-performance binary streaming. This lesson walks up that ladder with running examples: long polling, Server-Sent Events (SSE), WebSockets (including a small chat room), SignalR (shown on the wire, so you see what the library hides) and gRPC (read-only, because it needs a NuGet package and a code generator). At the end you will know which one to pick. The previous lessons on the request pipeline and minimal APIs are the prerequisites; channels and async streams are the in-process cousins of everything here.

Everything here runs on loopback inside one program: a Kestrel server and a client in the same process. In real life the two sit on different machines, connections can drop at any time, and you need reconnection logic, authentication and a plan for scaling out (more on that at the end). The using lines are implicit in a web project but must be written in our single-file runner.

The real-time ladder

Technique Direction How it works Notes
Short polling client asks, server answers The client repeats GET /updates every few seconds Simple, wasteful, always a little late
Long polling server pushes (kind of) The server holds the request open until it has news (or a timeout), then the client immediately asks again Works everywhere, one request per message
Server-Sent Events server to client One long-lived HTTP response of text/event-stream; the browser's EventSource reconnects automatically One-way, text, very simple
WebSockets both ways An HTTP request upgrades to a persistent, full-duplex message connection Low latency; you design the protocol
SignalR both ways A library on top of WebSockets (with fallbacks) that adds hubs, groups, method calls and reconnects The default choice for .NET interactive apps
gRPC streaming both ways Protobuf messages over HTTP/2 with generated clients Best for service-to-service; browsers need gRPC-Web

Long polling

With long polling the server does not answer a request until it has something to say. The client treats each reply as a message and sends the next request straight away, so updates arrive almost instantly with nothing but ordinary HTTP. The server needs a way to "wake up" waiting requests: a TaskCompletionSource<T> is the classic tool (see tasks). A timeout matters because proxies and browsers close connections that stay silent for too long.

C# Long polling with TaskCompletionSource

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.

Long polling is a fallback, not a goal: each message costs a full HTTP request and response, and a message published between two polls must be buffered or it is lost (this tiny version drops it). It still matters because SignalR uses it as the last-resort transport, and you will meet it in older systems.

Server-Sent Events

SSE is the simplest true push. The server answers one request with Content-Type: text/event-stream and keeps the response open, writing small text events as they happen. Each event is a few field: value lines ending with a blank line:

TEXT
id: 2
event: price
data: {"symbol":"MSFT","value":412.35}

In the browser, new EventSource("/stream") parses this, dispatches events by name, reconnects automatically after a drop, and resends the last id in a Last-Event-ID header so the server can resume. The channel is one-way (server to client), which is exactly what dashboards, progress bars, notifications and live logs need, and it works through ordinary HTTP infrastructure.

.NET 10 makes this a one-liner: TypedResults.ServerSentEvents(...) takes an IAsyncEnumerable<T> and writes the events for you. It pairs naturally with async iterators and yield return (see async streams). For control over id and event, yield SseItem<T> values. On the client side, the System.Net.ServerSentEvents namespace has an SseParser. The program shows the helper, the raw wire format written by hand, and the parser:

C# Server-Sent Events: helper, raw format and parser

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 block is the protocol itself: plain text, easy to debug with curl. The second shows the typed helper at work, where each decimal became the data: of one price event. The stream ends when the server's async sequence ends (a real feed would run until the client disconnects; the request's CancellationToken tells you when).

Choose SSE when you only need server to client updates. It uses plain HTTP (works with auth cookies, proxies and compression), the browser handles reconnection for you, and there is no protocol to design. Its limits: text only, one direction, and browsers cap the number of simultaneous connections per host on HTTP/1.1 (HTTP/2 removes that limit in practice).

WebSockets

A WebSocket starts as a normal HTTP request with an Upgrade: websocket header. If the server agrees, the same TCP connection switches protocols and becomes a bidirectional pipe that carries messages (text or binary) in both directions with very little overhead. Either side can send at any time. That is what chats, games and collaborative editors need.

In ASP.NET Core you enable the middleware with app.UseWebSockets(), then in an endpoint check context.WebSockets.IsWebSocketRequest and call AcceptWebSocketAsync(). You get a WebSocket object with ReceiveAsync and SendAsync. On the client, System.Net.WebSockets.ClientWebSocket does the other end (the browser has the WebSocket class).

Raw WebSockets give you no structure beyond messages. You decide the message format, how users are identified, how rooms work and how to detect dead connections. Three rules save beginners from the usual bugs:

  1. The endpoint must keep running as long as the socket is open. The framework closes the socket when your handler returns, so the handler contains the receive loop.
  2. Only one send at a time per socket. Calling SendAsync from several threads concurrently throws. Serialize sends (a SemaphoreSlim, or a per-connection channel).
  3. A message may arrive in pieces. Check EndOfMessage and keep reading until it is true (our messages are tiny, so one read is enough; production code should loop).

Here is a miniature chat room with two clients. The server keeps a dictionary of connected sockets and relays every message to all of them. A welcome message is sent first; the clients wait for it, which guarantees they are registered before anyone sends, so the output is the same on every run.

C# A WebSocket chat room

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.

Each message from one client reaches both clients, as the output shows. The Peer wrapper is the important design detail: the broadcast loop of one connection sends to the sockets of other connections, so two handlers may try to send to the same socket at once. The semaphore prevents that. Things this small demo leaves out and a real chat needs: authentication on the upgrade request, validating and limiting message sizes, heartbeats (ping/pong, or KeepAliveInterval) to detect dead peers, cleanup when a client vanishes without a close frame, and a message format (usually JSON with a type field).

SignalR: WebSockets with batteries

Writing all that by hand gets old fast. SignalR is the ASP.NET Core library that solves the common problems on top of WebSockets:

  • Hubs. You write a class deriving from Hub whose public methods clients can call. The server calls client methods by name with Clients.All.SendAsync("Receive", ...).
  • Targeting. Clients.All, Clients.Caller, Clients.Others, Clients.User(id), and groups (Groups.AddToGroupAsync) for rooms.
  • Transport fallback. WebSockets first, then Server-Sent Events, then long polling, negotiated automatically.
  • Reconnect, serialization and authentication integrated (JSON by default, MessagePack optional; the same [Authorize] and policies as the rest of the app).
  • Scale-out through a backplane (Redis, or the Azure SignalR Service) so several servers behave like one.

The server side of SignalR is part of the ASP.NET Core shared framework, so a hub can run in our environment. The ready-made client libraries (Microsoft.AspNetCore.SignalR.Client for .NET, @microsoft/signalr for JavaScript) are separate packages, so here is how you would use them, read-only:

C#
// Read-only: server (Program.cs and ChatHub.cs of a real project)
builder.Services.AddSignalR();
app.MapHub<ChatHub>("/chat");

public class ChatHub : Hub
{
    public async Task Send(string user, string text) =>
        await Clients.All.SendAsync("Receive", user, text);

    public Task Join(string room) => Groups.AddToGroupAsync(Context.ConnectionId, room);
}
JavaScript
// Read-only: browser client with the @microsoft/signalr package
const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chat")
    .withAutomaticReconnect()
    .build();

connection.on("Receive", (user, text) => console.log(`${user}: ${text}`));
await connection.start();
await connection.invoke("Send", "ada", "hello");

To see what the library does for you, the next program talks to a real hub without the client library, speaking the SignalR JSON protocol over a raw WebSocket. The protocol is tiny: every message is a JSON object followed by the ASCII "record separator" character (U+001E). The first message is a handshake that names the protocol; after that, type 1 is an invocation of a hub method, type 3 is the completion (result) of an invocation, and server-to-client calls arrive as type 1 messages too.

C# SignalR on the wire

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 lines. The handshake reply {} means "protocol accepted". The invocation Send("ada", "hello") made the hub call Clients.All.SendAsync("Receive", ...), which arrived at the (only) client as a type 1 message with target: "Receive". Finally the return value 5 came back in a type 3 completion tied to invocationId: "1". In a real application the client library does all this framing, correlates invocations with results and dispatches Receive to your handler.

(Skipping the usual POST /chat/negotiate step is allowed when you connect with WebSockets directly. Real clients negotiate to discover transports and the connection token.)

Hubs are transient. A new Hub instance is created for every call, so never store state in instance fields. Keep state in singleton services (injected into the hub) or a database, and remember that in-memory state does not survive a restart or a second server. Also validate every hub method argument and apply [Authorize]: hub methods are remotely callable entry points, just like API endpoints.

gRPC

gRPC is a remote-procedure-call framework built for service-to-service communication. You describe the contract in a .proto file; the tooling generates strongly typed clients and server base classes; messages travel as compact binary Protocol Buffers over HTTP/2. It supports four call shapes: unary (one request, one reply), server streaming, client streaming and bidirectional streaming.

gRPC lives in the NuGet packages Grpc.AspNetCore (server), Grpc.Net.Client and Google.Protobuf, plus a build-time code generator, none of which our runner has. The workflow in a real project looks like this:

TEXT
// Read-only: Protos/stock.proto
syntax = "proto3";
option csharp_namespace = "StockApi";

service StockTicker {
  rpc GetPrice (PriceRequest) returns (PriceReply);                  // unary
  rpc Watch (PriceRequest) returns (stream PriceReply);              // server streaming
}

message PriceRequest { string symbol = 1; }
message PriceReply   { string symbol = 1; double price = 2; }
C#
// Read-only: server implementation (the base class StockTicker.StockTickerBase is generated)
public class StockService : StockTicker.StockTickerBase
{
    public override Task<PriceReply> GetPrice(PriceRequest request, ServerCallContext context) =>
        Task.FromResult(new PriceReply { Symbol = request.Symbol, Price = 412.35 });

    public override async Task Watch(
        PriceRequest request, IServerStreamWriter<PriceReply> stream, ServerCallContext context)
    {
        double price = 412.35;
        while (!context.CancellationToken.IsCancellationRequested)
        {
            await stream.WriteAsync(new PriceReply { Symbol = request.Symbol, Price = price += 0.05 });
            await Task.Delay(1000, context.CancellationToken);
        }
    }
}

// Program.cs:  builder.Services.AddGrpc();   app.MapGrpcService<StockService>();

// Read-only: client
using var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new StockTicker.StockTickerClient(channel);
PriceReply reply = await client.GetPriceAsync(new PriceRequest { Symbol = "MSFT" });

Why teams pick gRPC for internal APIs: smaller and faster messages than JSON, a single source of truth for the contract (breaking changes show up as compile errors), built-in deadlines and cancellation, and first-class streaming. Why they do not for public APIs: browsers cannot speak native gRPC (they need the gRPC-Web adapter), the binary payloads are harder to inspect with simple tools, and every consumer needs the generated code or the .proto. The .proto rules for compatibility are strict about field numbers: never reuse or renumber them.

Choosing the right tool

  • Need updates in one direction only (feeds, progress, notifications)? Server-Sent Events. Simplest thing that works.
  • Interactive and two-way (chat, collaboration, live dashboards with commands) in a .NET app? SignalR. Do not hand-roll groups, reconnection and scale-out.
  • Raw, custom or binary protocols, or non-.NET clients speaking a standard protocol? WebSockets directly.
  • Service-to-service calls with strict contracts and streaming? gRPC.
  • Constrained to plain HTTP infrastructure or very old clients? Long polling (usually as SignalR's automatic fallback).

Production concerns

  • Scale-out. A connection lives on one server, so a message sent on server A will not reach clients on server B unless you add a backplane (Redis for SignalR) or use a managed service. Load balancers need sticky sessions for SignalR's non-WebSocket transports.
  • Idle timeouts. Proxies and load balancers close silent connections; send keep-alives (SignalR does by default; set KeepAliveInterval for raw WebSockets).
  • Authentication. Browsers cannot set headers on WebSocket or EventSource requests, so credentials usually travel in cookies or a short-lived token in the query string. Treat such URLs as sensitive in logs.
  • Back-pressure. A slow client must not make the server's memory grow without limit; use bounded queues (bounded channels) and disconnect clients that cannot keep up.
  • Limits. Cap message sizes and connections per user, validate all input, and handle disconnects as a normal event, not an error.
  • Reconnection and missed messages. Connections drop. Design so a reconnecting client can resume (event ids, sequence numbers) or reload state from a normal API.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which technique fits a one-way live feed (such as a progress bar or notifications) best, with automatic browser reconnection?

    SSE is a one-way text stream over plain HTTP, and the browser's EventSource reconnects automatically and sends Last-Event-ID so the server can resume.
  2. 2. Why must a WebSocket endpoint handler keep running (for example in a receive loop) while the connection is open?

    After AcceptWebSocketAsync the request is still the one being processed. When the endpoint delegate completes, the framework ends the request and the connection is closed.
  3. 3. What is true about concurrent sends on one WebSocket object?

    WebSocket.SendAsync is not safe to call concurrently. Use a lock such as a SemaphoreSlim or a per-connection channel to serialize writers.
  4. 4. What should you do with state in a SignalR Hub class?

    Hub instances are transient. Per-connection or shared state belongs in injected singleton services (thread-safe) or a database.
  5. 5. What is the main reason to choose gRPC for communication between two backend services?

    gRPC uses Protocol Buffers over HTTP/2, a contract-first workflow that generates clients and servers, and supports streaming. Browsers need gRPC-Web to use it.

Summary

  • Real-time options range from long polling (plain HTTP tricks) through Server-Sent Events (one-way push) and WebSockets (two-way messages) to SignalR (hubs, groups, fallbacks) and gRPC (typed binary streaming between services).
  • SSE is the simplest for server-to-client updates; TypedResults.ServerSentEvents in .NET 10 writes the stream from an IAsyncEnumerable<T>.
  • A WebSocket handler must stay alive for the whole connection; serialize sends per socket, handle partial messages, and design your own message format, authentication and heartbeats.
  • SignalR's server runs inside ASP.NET Core; on the wire it is JSON frames separated by U+001E. Hubs are transient, so keep state elsewhere and secure every method.
  • gRPC needs NuGet packages and a .proto contract; use it for internal service calls, and keep field numbers stable.
  • In production plan for scale-out (backplane), idle timeouts, back-pressure, reconnection and resuming after missed messages.

Next: Publishing and Deploying .NET Apps