{"id":160,"date":"2025-06-30T09:00:15","date_gmt":"2025-06-30T07:00:15","guid":{"rendered":"https:\/\/www.insync.co.za\/blog\/?p=160"},"modified":"2025-06-30T09:00:16","modified_gmt":"2025-06-30T07:00:16","slug":"real-time-communication-with-websockets-in-c","status":"publish","type":"post","link":"https:\/\/www.insync.co.za\/blog\/2025\/06\/30\/real-time-communication-with-websockets-in-c\/","title":{"rendered":"Real-Time Communication with WebSockets in C#"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">In the world of modern applications, real-time communication is more than a feature\u2014it&#8217;s an expectation. Whether you&#8217;re building a chat app, live notification system, collaborative tools, or dashboards, <strong>WebSockets<\/strong> offer a powerful way to deliver seamless, bi-directional communication between the client and server.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this post, we&#8217;ll dive into how you can use WebSockets in C# to enable real-time capabilities in your application.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">What Are WebSockets?<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">WebSockets are a communication protocol providing <strong>full-duplex<\/strong> communication channels over a single TCP connection. Unlike HTTP, which follows a request-response model, WebSockets allow either party to send messages <strong>independently<\/strong>, making them ideal for real-time applications.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Why Use WebSockets?<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>No need to poll the server<\/li>\n\n\n\n<li>Lower latency<\/li>\n\n\n\n<li>Persistent connection<\/li>\n\n\n\n<li>Real-time message delivery<\/li>\n\n\n\n<li>Ideal for chat apps, live notifications, gaming, stock tickers, collaborative editing tools<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Getting Started in C#<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Tools You Need:<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>.NET 6 or later (though it works in .NET Core 3.1+)<\/li>\n\n\n\n<li>ASP.NET Core Web App or API<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Step 1: Create a WebSocket Middleware<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Let\u2019s build a simple WebSocket server in ASP.NET Core.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-a044e364787c835e9469a7b55ad7a4da\">csharpCopyEdit<code>public class WebSocketMiddleware\n{\n    private readonly RequestDelegate _next;\n\n    public WebSocketMiddleware(RequestDelegate next)\n    {\n        _next = next;\n    }\n\n    public async Task InvokeAsync(HttpContext context)\n    {\n        if (context.Request.Path == \"\/ws\")\n        {\n            if (context.WebSockets.IsWebSocketRequest)\n            {\n                using var webSocket = await context.WebSockets.AcceptWebSocketAsync();\n                await Echo(context, webSocket);\n            }\n            else\n            {\n                context.Response.StatusCode = 400;\n            }\n        }\n        else\n        {\n            await _next(context);\n        }\n    }\n\n    private async Task Echo(HttpContext context, WebSocket webSocket)\n    {\n        var buffer = new byte[1024 * 4];\n        WebSocketReceiveResult result;\n\n        do\n        {\n            result = await webSocket.ReceiveAsync(new ArraySegment&lt;byte&gt;(buffer), CancellationToken.None);\n            var message = Encoding.UTF8.GetString(buffer, 0, result.Count);\n            Console.WriteLine($\"Received: {message}\");\n\n            var response = Encoding.UTF8.GetBytes($\"Echo: {message}\");\n            await webSocket.SendAsync(new ArraySegment&lt;byte&gt;(response), result.MessageType, result.EndOfMessage, CancellationToken.None);\n\n        } while (!result.CloseStatus.HasValue);\n\n        await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);\n    }\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">Step 2: Register Middleware in <code>Startup.cs<\/code><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For .NET 6+, update your <code>Program.cs<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-294e00bbb4171756ec921cc9e38930a6\">csharpCopyEdit<code>var builder = WebApplication.CreateBuilder(args);\nvar app = builder.Build();\n\napp.UseWebSockets();\n\napp.UseMiddleware&lt;WebSocketMiddleware&gt;();\n\napp.Run();\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Testing It Out<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">You can use browser-based tools like <a class=\"\" href=\"https:\/\/websocketking.com\/\">WebSocket King Client<\/a> or JavaScript in the browser console:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-c08b4a6e6ba06f75352d9f56d114fb62\">jsCopyEdit<code>const socket = new WebSocket(\"ws:\/\/localhost:5000\/ws\");\n\nsocket.onmessage = (event) =&gt; console.log(\"Message from server:\", event.data);\n\nsocket.onopen = () =&gt; {\n  console.log(\"Connected\");\n  socket.send(\"Hello WebSocket Server!\");\n};\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Considerations<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Authentication<\/strong>: WebSockets don\u2019t work directly with cookie\/session-based auth. Consider token-based approaches (like JWT).<\/li>\n\n\n\n<li><strong>Scaling<\/strong>: For scale-out, use a message broker (like Redis Pub\/Sub) to sync WebSocket servers.<\/li>\n\n\n\n<li><strong>Keep-alive\/heartbeats<\/strong>: Implement ping\/pong frames or timeouts to detect dead connections.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Bonus: Use WebSocket Libraries<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">While ASP.NET Core\u2019s built-in support is solid, there are higher-level libraries that abstract away some boilerplate:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a class=\"\" href=\"https:\/\/learn.microsoft.com\/en-us\/aspnet\/core\/signalr\/introduction\">SignalR<\/a> (built on WebSockets, supports fallback, groups, auto reconnection, etc.)<\/li>\n\n\n\n<li><a class=\"\" href=\"https:\/\/github.com\/statianzo\/Fleck\">Fleck<\/a> \u2013 WebSocket server implementation for .NET<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\u2705 Conclusion<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">WebSockets in C# offer a powerful, efficient way to build real-time features into your app. Whether you&#8217;re building a live dashboard, multiplayer game, or collaborative tool, the WebSocket API gives you the tools to handle modern, responsive communication needs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Keep it simple when you can, and scale wisely when you must.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>\ud83d\udd17 Want to explore more?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can find this and other insightful dev articles on our <a class=\"\" href=\"https:\/\/insync.co.za\">InSync blog<\/a> \u2014 from C# and Angular tips to scaling real-world SaaS tools.<br>\ud83d\udc49 <a class=\"\" href=\"https:\/\/insync.co.za\">Browse all our blog posts here<\/a><br>Looking for custom software development or consulting? Visit our <a class=\"\" href=\"https:\/\/insync.co.za\">main website<\/a> and let\u2019s build something great together.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In the world of modern applications, real-time communication is more than a feature\u2014it&#8217;s an expectation. Whether you&#8217;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&#8217;ll dive into how you can use WebSockets in [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":164,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"pagelayer_contact_templates":[],"_pagelayer_content":"","footnotes":""},"categories":[18],"tags":[30,33,31,29],"class_list":["post-160","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-software-development","tag-c","tag-middleware","tag-signalr","tag-websocket"],"_links":{"self":[{"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/posts\/160","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/comments?post=160"}],"version-history":[{"count":2,"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/posts\/160\/revisions"}],"predecessor-version":[{"id":165,"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/posts\/160\/revisions\/165"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/media\/164"}],"wp:attachment":[{"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/media?parent=160"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/categories?post=160"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/tags?post=160"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}