Real-time transport choices
Real-time transport choices
Choose a transport by the interaction it must support, not by whether it sounds modern. Ordinary HTTP request/reply, server-sent events (SSE), raw WebSockets, SignalR and gRPC solve different communication problems and impose different recovery costs.
Ordinary HTTP is suitable for occasional queries or mutations. SSE sends a server-to-browser event stream over HTTP; the browser can issue separate requests for commands. Its text framing uses lines and a blank line between events. WebSockets provide bidirectional messages, but a receive may return a fragment rather than a complete message. Bound assembled size, handle close frames and cancellation, and keep the request pipeline active until socket work ends. SignalR adds hub invocation, client callbacks and groups over negotiated transports. Native gRPC suits typed service-to-service contracts and streaming; browser support differs. For all persistent connections design authorization, backpressure, reconnect, resource limits and message replay. WebSocket origins require separate validation for browsers; CORS is not an authorization system or a complete WebSocket origin defense. These public synthetic loopback examples are finite and are not deployable security configurations.
Baseline: .NET 10 / C# 14. In an approved environment use the complete fixture project, restore only reviewed dependencies from approved sources, then run dotnet build --no-restore and dotnet run --no-build --no-launch-profile. Blazor projects use localhost:5087; stop the server with Ctrl+C. Other examples start a bounded local server and client in one process. No real credentials or external services. Expected results are reasoned, not executed.
Use request/reply for a snapshot
One local HTTP request retrieves the current synthetic count.
using System.Net;using System.Net.WebSockets;using System.Text;var builder = WebApplication.CreateBuilder(args);builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(o => o.Listen(IPAddress.Loopback, 0));await using var app = builder.Build();using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15));app.MapGet("/stock", () => "4");await app.StartAsync(timeout.Token);try {using var client = new HttpClient();Console.WriteLine(await client.GetStringAsync(app.Urls.Single() + "/stock", timeout.Token));} finally { await app.StopAsync(); }Expected result (not executed):
4No persistent stream is needed for an occasional snapshot.
Read two finite SSE frames
Read a short event stream without a browser dependency.
using System.Net;using System.Net.WebSockets;using System.Text;var builder = WebApplication.CreateBuilder(args);builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(o => o.Listen(IPAddress.Loopback, 0));await using var app = builder.Build();using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15));app.MapGet("/events", async (HttpContext ctx) => { ctx.Response.ContentType = "text/event-stream"; foreach (int n in new[] { 4, 3 }) { await ctx.Response.WriteAsync($"data: {n}\n\n", ctx.RequestAborted); await ctx.Response.Body.FlushAsync(ctx.RequestAborted); }});await app.StartAsync(timeout.Token);try {using var client = new HttpClient();using var response = await client.GetAsync(app.Urls.Single() + "/events", HttpCompletionOption.ResponseHeadersRead, timeout.Token);response.EnsureSuccessStatusCode();using var reader = new StreamReader(await response.Content.ReadAsStreamAsync(timeout.Token));while (await reader.ReadLineAsync(timeout.Token) is string line) if (line.StartsWith("data: ", StringComparison.Ordinal)) Console.WriteLine(line[6..]);} finally { await app.StopAsync(); }Expected result (not executed):
43The fixture is a simple data-only SSE reader, not a complete EventSource parser or replay implementation.
Assemble one fragmented WebSocket message
The local client sends two fragments; the server caps the full message at 64 bytes.
using System.Net;using System.Net.WebSockets;using System.Text;var builder = WebApplication.CreateBuilder(args);builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(o => o.Listen(IPAddress.Loopback, 0));await using var app = builder.Build();using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15));app.UseWebSockets();app.MapGet("/socket", async (HttpContext ctx) => { if (!ctx.WebSockets.IsWebSocketRequest) { ctx.Response.StatusCode = 400; return; } using var socket = await ctx.WebSockets.AcceptWebSocketAsync(); using var limit = CancellationTokenSource.CreateLinkedTokenSource(ctx.RequestAborted); limit.CancelAfter(TimeSpan.FromSeconds(10)); byte[] buffer = new byte[8]; using var message = new MemoryStream(); while (true) { var part = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), limit.Token); if (part.MessageType == WebSocketMessageType.Close) { await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Done", limit.Token); return; } if (part.MessageType != WebSocketMessageType.Text || message.Length + part.Count > 64) { await socket.CloseOutputAsync(WebSocketCloseStatus.PolicyViolation, "Unsupported message", limit.Token); return; } message.Write(buffer, 0, part.Count); if (part.EndOfMessage) break; } await socket.SendAsync(new ArraySegment<byte>(message.ToArray()), WebSocketMessageType.Text, true, limit.Token); await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", limit.Token);});await app.StartAsync(timeout.Token);try {using var socket = new ClientWebSocket();await socket.ConnectAsync(new Uri(app.Urls.Single().Replace("http://", "ws://") + "/socket"), timeout.Token);await socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("At")), WebSocketMessageType.Text, false, timeout.Token);await socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("las")), WebSocketMessageType.Text, true, timeout.Token);byte[] buffer = new byte[8]; using var result = new MemoryStream();while (true) { var part = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), timeout.Token); if (part.MessageType != WebSocketMessageType.Text || result.Length + part.Count > 64) throw new InvalidOperationException("Unexpected response"); result.Write(buffer, 0, part.Count); if (part.EndOfMessage) break;}Console.WriteLine(Encoding.UTF8.GetString(result.ToArray()));var close = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), timeout.Token);if (close.MessageType == WebSocketMessageType.Close) await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Done", timeout.Token);} finally { await app.StopAsync(); }Expected result (not executed):
AtlasReceive boundaries need not match send boundaries; assemble until EndOfMessage and respond to the close handshake.
Apply the concept
Choose transports for hourly price lookup, a live public ticker, a collaborative browser app and typed internal inventory RPC. Explain recovery and security for each.
Use the manual practice and knowledge check to reason about the boundary. Do not deploy these local demonstrations as production services.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Real-time transport choices — knowledge check
Apply the lesson concepts to the following scenarios.
Which transport fits occasional snapshot reads?
What separates simple SSE events?
When is a received WebSocket message complete?
Does CORS alone enforce WebSocket origin security?
What is a reason to choose SignalR over raw WebSockets?