Real-Time Communication with WebSockets in C#
In the world of modern applications, real-time communication is more than a feature—it’s an expectation. Whether you’re building a chat app, live notification system, collaborative tools, or dashboards, WebSockets offer a powerful way to deliver seamless, bi-directional communication between the client and server.
In this post, we’ll dive into how you can use WebSockets in C# to enable real-time capabilities in your application.
What Are WebSockets?
WebSockets are a communication protocol providing full-duplex communication channels over a single TCP connection. Unlike HTTP, which follows a request-response model, WebSockets allow either party to send messages independently, making them ideal for real-time applications.
Why Use WebSockets?
- No need to poll the server
- Lower latency
- Persistent connection
- Real-time message delivery
- Ideal for chat apps, live notifications, gaming, stock tickers, collaborative editing tools
Getting Started in C#
Tools You Need:
- .NET 6 or later (though it works in .NET Core 3.1+)
- ASP.NET Core Web App or API
Step 1: Create a WebSocket Middleware
Let’s build a simple WebSocket server in ASP.NET Core.
csharpCopyEditpublic class WebSocketMiddleware
{
private readonly RequestDelegate _next;
public WebSocketMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (context.Request.Path == "/ws")
{
if (context.WebSockets.IsWebSocketRequest)
{
using var webSocket = await context.WebSockets.AcceptWebSocketAsync();
await Echo(context, webSocket);
}
else
{
context.Response.StatusCode = 400;
}
}
else
{
await _next(context);
}
}
private async Task Echo(HttpContext context, WebSocket webSocket)
{
var buffer = new byte[1024 * 4];
WebSocketReceiveResult result;
do
{
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
var message = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine($"Received: {message}");
var response = Encoding.UTF8.GetBytes($"Echo: {message}");
await webSocket.SendAsync(new ArraySegment<byte>(response), result.MessageType, result.EndOfMessage, CancellationToken.None);
} while (!result.CloseStatus.HasValue);
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
}
Step 2: Register Middleware in Startup.cs
For .NET 6+, update your Program.cs:
csharpCopyEditvar builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseWebSockets();
app.UseMiddleware<WebSocketMiddleware>();
app.Run();
Testing It Out
You can use browser-based tools like WebSocket King Client or JavaScript in the browser console:
jsCopyEditconst socket = new WebSocket("ws://localhost:5000/ws");
socket.onmessage = (event) => console.log("Message from server:", event.data);
socket.onopen = () => {
console.log("Connected");
socket.send("Hello WebSocket Server!");
};
Considerations
- Authentication: WebSockets don’t work directly with cookie/session-based auth. Consider token-based approaches (like JWT).
- Scaling: For scale-out, use a message broker (like Redis Pub/Sub) to sync WebSocket servers.
- Keep-alive/heartbeats: Implement ping/pong frames or timeouts to detect dead connections.
Bonus: Use WebSocket Libraries
While ASP.NET Core’s built-in support is solid, there are higher-level libraries that abstract away some boilerplate:
- SignalR (built on WebSockets, supports fallback, groups, auto reconnection, etc.)
- Fleck – WebSocket server implementation for .NET
✅ Conclusion
WebSockets in C# offer a powerful, efficient way to build real-time features into your app. Whether you’re building a live dashboard, multiplayer game, or collaborative tool, the WebSocket API gives you the tools to handle modern, responsive communication needs.
Keep it simple when you can, and scale wisely when you must.
🔗 Want to explore more?
You can find this and other insightful dev articles on our InSync blog — from C# and Angular tips to scaling real-world SaaS tools.
👉 Browse all our blog posts here
Looking for custom software development or consulting? Visit our main website and let’s build something great together.