WebSocket in C#: Creating Real-Time Applications with .NET

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to WebSocket in C# for Real-Time Applications

Modern web applications increasingly require instant data transfer between client and server. The traditional HTTP protocol, operating on a "request-response" scheme, is inefficient for tasks where low latency and constant information updates are important: online chats, stock quotes, multiplayer games, monitoring systems. WebSocket comes to the rescue — a protocol that provides a persistent two-way connection.

In the C# (.NET) ecosystem, WebSocket implementation is available both through the built-in classes of the System.Net.WebSockets namespace and through the high-level SignalR library. In this article, we will cover both approaches, write working examples, and discuss architectural features of real-time applications. The material will be useful for both beginner and experienced .NET developers.



WebSocket Basics: How It Works in C#

WebSocket is a protocol that, after an initial HTTP handshake (upgrade request), transitions the connection into a persistent bidirectional mode. In C#, working with WebSocket is built on asynchronous programming using the async and await keywords.



Creating a Simple WebSocket Server in C#

Let's look at a basic example of a server that accepts WebSocket connections and echoes back to the client. For this, we use the built-in HttpListener class or Kestrel (ASP.NET Core). Below is an example based on ASP.NET Core.

// Startup.cs or Program.cs (minimal API)var builder = WebApplication.CreateBuilder(args);var app = builder.Build();

app.UseWebSockets();

app.Map("/ws", async (HttpContext context) =>{ if (context.WebSockets.IsWebSocketRequest) { using var webSocket = await context.WebSockets.AcceptWebSocketAsync(); await Echo(webSocket); } else { context.Response.StatusCode = 400; }});

async Task Echo(WebSocket webSocket){ var buffer = new byte[1024 * 4]; while (webSocket.State == WebSocketState.Open) { var result = await webSocket.ReceiveAsync( new ArraySegment<byte>(buffer), CancellationToken.None); if (result.MessageType == WebSocketMessageType.Close) { await webSocket.CloseAsync( WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None); } else { // Send data back (echo) await webSocket.SendAsync( new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); } }}

app.Run();

The code demonstrates the basic mechanics: AcceptWebSocketAsync upgrades the HTTP request to WebSocket, and the ReceiveAsync and SendAsync methods provide asynchronous data exchange. It is important to handle the connection state and close it properly.



WebSocket Client in C#

The client side is also simple. Use the ClientWebSocket class:

using System.Net.WebSockets;

async Task ConnectAndSend(){ using var client = new ClientWebSocket(); await client.ConnectAsync(new Uri("ws://localhost:5000/ws"), CancellationToken.None);

var message = "Hello, WebSocket!"; var bytes = Encoding.UTF8.GetBytes(message); await client.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, CancellationToken.None);

var buffer = new byte[1024]; var result = await client.ReceiveAsync( new ArraySegment<byte>(buffer), CancellationToken.None); var response = Encoding.UTF8.GetString(buffer, 0, result.Count); Console.WriteLine($"Re

Blogs

Book Recommendations