{"id":794,"date":"2023-08-04T01:15:04","date_gmt":"2023-08-04T01:15:04","guid":{"rendered":"https:\/\/www.w3computing.com\/articles\/?p=794"},"modified":"2023-08-23T16:20:28","modified_gmt":"2023-08-23T16:20:28","slug":"real-time-chat-application-signalr-csharp","status":"publish","type":"post","link":"https:\/\/www.w3computing.com\/articles\/real-time-chat-application-signalr-csharp\/","title":{"rendered":"Build a Real-Time Chat Application with SignalR in C#"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">Introduction<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Real-time communication has become a fundamental part of the digital world. Whether it&#8217;s instant messaging, live video streaming, or multiplayer online games, real-time communication delivers instantaneous, bidirectional communication between users over the internet. This enables interactions that are as close as possible to face-to-face communication, but with the flexibility and convenience of digital.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this context, real-time chat applications have emerged as powerful tools, creating a seamless communication channel that transcends geographical barriers. With the rise in remote work, online learning, and digital social interactions, these applications have become even more crucial. They offer immediate exchange of messages, fostering collaboration, improving productivity, and enabling social connections in ways that traditional methods cannot compete with.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">SignalR, a software library for Microsoft .NET, plays a critical role in enabling such real-time communication. It simplifies the process of adding real-time web functionality to applications, allowing them to automatically push content updates to connected clients as they happen, rather than requiring clients to poll the server for updates.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">SignalR&#8217;s main function in real-time communication is managing connections between servers and clients. It automatically handles connection management, supports broadcasting messages to all connected clients, and allows the sending of messages to specific clients. What makes SignalR stand out is its ability to automatically select the best transport method based on the server and client capabilities. Whether it&#8217;s WebSockets, Server-Sent Events, or Long Polling, SignalR can switch between these transport protocols to ensure that your application works consistently across different environments.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Moreover, SignalR offers features such as automatic reconnection, scaling out to handle a large number of connections, and providing detailed error information. These benefits make it an excellent choice for developing real-time applications, particularly real-time chat applications.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The C# language, a multi-paradigm programming language developed by Microsoft, is integral in building such applications with SignalR. C#, being a part of the .NET ecosystem just like SignalR, enables seamless integration and provides robust, efficient, and secure code that is needed for real-time communication. Its object-oriented nature helps developers create maintainable and scalable applications.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This article is aimed at intermediate to advanced developers who have a basic understanding of C#, .NET Core, and web development concepts. By the end of this guide, you will learn how to build a real-time chat application using SignalR in C#, offering a practical approach with code examples for each step. So, get your developer hat on, and let&#8217;s dive into the world of real-time application development!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Before we embark on this journey of creating a real-time chat application with SignalR in C#, it&#8217;s essential to establish what knowledge and software you&#8217;ll need. Let&#8217;s break it down:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Basic Knowledge Requirements:<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To ensure a smooth and productive experience, you should have:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>C# Basics:<\/strong> An understanding of C# programming language fundamentals, including variables, data types, operators, loops, conditions, and functions, is essential. Familiarity with object-oriented programming concepts, such as classes, objects, inheritance, and polymorphism, will be beneficial since C# is an object-oriented language.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Familiarity with ASP.NET Core:<\/strong> Our project will be based on the ASP.NET Core framework, which means you&#8217;ll need to understand its core concepts, such as middleware, dependency injection, controllers, and views. Knowledge of the MVC (Model-View-Controller) design pattern would be beneficial.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Understanding of JavaScript\/jQuery:<\/strong> Since SignalR uses JavaScript to manage client-side connections and receive real-time updates, basic knowledge of JavaScript and its popular library, jQuery, is necessary. This includes understanding JavaScript syntax, variables, functions, and events, along with jQuery&#8217;s DOM manipulation techniques.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Knowledge of HTML and CSS:<\/strong> The visual aspects of our chat application will be created using HTML and CSS. Therefore, you should understand HTML tags, attributes, and CSS selectors, properties, and styling techniques.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Software Requirements:<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Here are the software tools you&#8217;ll need:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Development Environment:<\/strong> You need an Integrated Development Environment (IDE) to write and debug your code. Visual Studio 2019 or later, or Visual Studio Code, are recommended as they offer excellent support for C# and ASP.NET Core development.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>.NET Core SDK:<\/strong> To develop an ASP.NET Core application, you&#8217;ll need the .NET Core Software Development Kit (SDK). You can download the latest stable version from the official Microsoft website.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Web Browser:<\/strong> A modern web browser (like Google Chrome, Mozilla Firefox, or Microsoft Edge) is required to test and interact with your application.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Node.js and npm:<\/strong> For managing and running client-side packages, you should have Node.js and npm (Node Package Manager) installed on your system.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By having these prerequisites in place, you can comfortably follow along and get the most out of the upcoming sections as we build our real-time chat application using SignalR in C#.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Understanding SignalR<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">SignalR is a Microsoft .NET library that empowers developers to add real-time web functionality to applications. This real-time functionality allows server-side code to push content updates to connected clients instantly, as they occur, not requiring the client to send a request for each new update.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">An Overview of SignalR<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In contrast to traditional request-response communication where the client initiates communication, SignalR provides a persistent connection between the client and the server. This two-way communication channel enables the server to send updates and messages to the client in real-time, making it excellent for applications that require high-frequency updates from the server, such as live chat, real-time gaming, and collaborative online applications.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Understanding Hubs in SignalR<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A core concept in SignalR is a &#8220;Hub.&#8221; Hubs provide a higher-level pipeline that allows your client and server to call methods on each other directly. A Hub can be considered as a communication center where messages are passed from one client to all other clients or specific ones.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">On the server side, you define methods that can be called by clients. On the client side, you define methods that the server can call. This dynamic interaction between server and clients sets the groundwork for our real-time chat application.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How SignalR Works<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">SignalR makes use of a variety of techniques under the hood to establish a real-time, two-way communication channel. It automatically chooses the best transport protocol based on the server and client capabilities.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">SignalR Connection Lifecycle<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The lifecycle of a SignalR connection starts with the client invoking a connection to the server. Once the server acknowledges this connection, a persistent two-way communication channel is established. Both the client and server can now freely exchange data until the connection is terminated either by the client, the server, or due to network issues. Upon disconnection, SignalR allows automatic reconnection, ensuring consistent communication.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Transport Protocols used by SignalR<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The key transport methods used by SignalR are:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>WebSockets:<\/strong> This full-duplex communication channel allows both client and server to send messages simultaneously without closing the connection. SignalR uses WebSockets whenever the server and client support it.<\/li>\n\n\n\n<li><strong>Server-Sent Events:<\/strong> Here, the server sends updates to the client over a persistent HTTP connection. This is used when the client supports it, and WebSockets are not available.<\/li>\n\n\n\n<li><strong>Long Polling:<\/strong> As a last resort, when both WebSockets and Server-Sent Events are unavailable, SignalR uses Long Polling. The client sends a request to the server, and if there are no updates, the server holds the request until there are updates, or a timeout occurs.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">When to Use SignalR<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">SignalR is the perfect choice when your application needs real-time functionality like a chat application, live updates (like in a sports event), real-time monitoring applications, and collaborative applications (like Google Docs). It removes the complexity of setting up and managing connections, handling varying transport methods, and maintaining a seamless experience across different environments.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Project Overview<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Defining the Goal of the Project<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Our objective in this project is to develop a real-time chat application using SignalR in C#. This chat application will allow multiple users to communicate with each other in real-time, displaying new messages instantly without requiring users to refresh or perform any action to retrieve these messages.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Discussing the Project&#8217;s Structure<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The project will follow the structure of a typical ASP.NET Core application, separated into client-side and server-side components:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Client-side:<\/strong> The client-side of our application will comprise HTML, CSS, and JavaScript to create a user-friendly interface where users can send and receive messages. We will use JavaScript and the SignalR library to establish and manage a connection to the server, send messages to the server, and update the chat window when new messages arrive from the server.<\/li>\n\n\n\n<li><strong>Server-side:<\/strong> On the server-side, we will use C# to create an ASP.NET Core project. The server will host a SignalR &#8220;Hub&#8221; that clients connect to, send messages to, and receive messages from. It will manage all the connected clients and broadcast incoming messages to all users.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ll also make use of MVC architecture, keeping our application well-structured and manageable.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">List of Features in our Chat Application<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Our real-time chat application will include the following core features:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>User Connections:<\/strong> Users can connect to and disconnect from the chat room. Upon connection, all current users will be notified of the new user&#8217;s arrival.<\/li>\n\n\n\n<li><strong>Real-time Messaging:<\/strong> Users can send messages to the chat room. Messages from any user appear in the chat window of all users in real-time, without requiring a page refresh.<\/li>\n\n\n\n<li><strong>User List:<\/strong> The application will maintain and display a list of connected users. This list will update in real-time as users join or leave the chat room.<\/li>\n\n\n\n<li><strong>Message History:<\/strong> The chat application will also provide a history of messages to newly connected users, ensuring they can catch up with the conversation.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">As we proceed with building the application, you can extend the list of features based on the application&#8217;s requirements. For instance, you may want to add private messaging between users, message reactions, or user is typing indicators. For now, our focus will be on creating a robust and functional real-time chat application with the core features outlined above.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step-by-step Guide to Building a Real-Time Chat Application<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">After laying the groundwork in the previous sections, it&#8217;s time to dive into building our real-time chat application with SignalR in C#. Let&#8217;s break down the entire process into manageable steps, starting with the project creation and setup.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Creating the Project<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">First, we need to create an ASP.NET Core project. This will serve as the backbone of our application, providing the web server and framework for building the chat application.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can create the project by running the following command in your terminal or command prompt:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Bash\" data-shcb-language-slug=\"bash\"><span><code class=\"hljs language-bash\">dotnet new webapp -o ChatApp<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Bash<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">bash<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">This command creates a new ASP.NET Core web application named &#8220;ChatApp&#8221;.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">After running the command, navigate into the new project directory:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Bash\" data-shcb-language-slug=\"bash\"><span><code class=\"hljs language-bash\"><span class=\"hljs-built_in\">cd<\/span> ChatApp<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Bash<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">bash<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Now, you should be inside your project&#8217;s root directory, ready to start building the application.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Setting up the Project in ASP.NET Core<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">After creating the project, open it in your preferred code editor. You&#8217;ll notice a number of files and folders have been created for you. The key files you&#8217;ll be working with are:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>Startup.cs<\/code>: This file contains the startup settings for your application. You&#8217;ll add your SignalR hub configuration here.<\/li>\n\n\n\n<li><code>wwwroot<\/code>: This directory contains your static files, including HTML, CSS, and JavaScript files.<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">Creating Necessary Folders and Files<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">First, you need to create a new folder for your SignalR hubs. In the root of your project, create a new folder named <code>Hubs<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Inside the <code>Hubs<\/code> folder, create a new file named <code>ChatHub.cs<\/code>. This will be your SignalR hub for handling real-time chat communication.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Your <code>ChatHub.cs<\/code> file should look like this to start:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">using<\/span> Microsoft.AspNetCore.SignalR;\n<span class=\"hljs-keyword\">using<\/span> System.Threading.Tasks;\n\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">ChatHub<\/span> : <span class=\"hljs-title\">Hub<\/span>\n{\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> Task <span class=\"hljs-title\">SendMessage<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">string<\/span> user, <span class=\"hljs-keyword\">string<\/span> message<\/span>)<\/span>\n    {\n        <span class=\"hljs-keyword\">return<\/span> Clients.All.SendAsync(<span class=\"hljs-string\">\"ReceiveMessage\"<\/span>, user, message);\n    }\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">This code sets up a basic SignalR hub with a single method, <code>SendMessage<\/code>, which broadcasts a message to all connected clients.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Next, create your front-end files. In the <code>wwwroot<\/code> directory, create a new HTML file named <code>chat.html<\/code>. This will be the HTML for your chat interface.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Also, in the <code>wwwroot<\/code> directory, create a new JavaScript file named <code>chat.js<\/code>. This is where you&#8217;ll write the JavaScript code to handle sending and receiving chat messages using SignalR.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, ensure that the SignalR client library is added to your project. You can add it by including the following script tag in your <code>chat.html<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"HTML, XML\" data-shcb-language-slug=\"xml\"><span><code class=\"hljs language-xml\"><span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">script<\/span> <span class=\"hljs-attr\">src<\/span>=<span class=\"hljs-string\">\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/microsoft-signalr\/3.1.7\/signalr.min.js\"<\/span>&gt;<\/span><span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">script<\/span>&gt;<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">HTML, XML<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">xml<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Setting Up SignalR<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">SignalR is a part of the ASP.NET Core framework, providing the necessary tools to create real-time, server-side functionality in your web application. Let&#8217;s begin by setting up SignalR for our project.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Installation and Configuration<\/h4>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Create an ASP.NET Core project:<\/strong> Start by creating a new ASP.NET Core project. You can do this through Visual Studio (File &gt; New &gt; Project, then choose &#8220;ASP.NET Core Web Application&#8221;) or via .NET CLI using the command <code>dotnet new webapp -o MyChatApp<\/code>.<\/li>\n\n\n\n<li><strong>Install SignalR:<\/strong> Since ASP.NET Core 3.0, SignalR is included in the framework by default. If you are using an older version of ASP.NET Core, you will need to install the SignalR library manually. You can install it via NuGet package manager using the command <code>Install-Package Microsoft.AspNetCore.SignalR<\/code> or through .NET CLI using the command <code>dotnet add package Microsoft.AspNetCore.SignalR<\/code>.<\/li>\n\n\n\n<li><strong>Configure SignalR in Startup.cs:<\/strong> In the Startup.cs file, you need to add SignalR to the middleware pipeline. This is done in two steps:\n<ul class=\"wp-block-list\">\n<li>In the <code>ConfigureServices<\/code> method, add <code>services.AddSignalR();<\/code>.<\/li>\n\n\n\n<li>In the <code>Configure<\/code> method, append <code>endpoints.MapHub&lt;YourHubClass&gt;(\"\/yourhubpath\");<\/code> inside the <code>UseEndpoints<\/code> method. This maps requests to your defined hub.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h4 class=\"wp-block-heading\">Creating a SignalR Hub<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The SignalR Hub is a class that acts as a high-level pipeline allowing the client and server to call methods on each other. To create a hub:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Create a new class for the hub:<\/strong> In your project, create a new class file named <code>ChatHub.cs<\/code> (or a name of your choice).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Inherit from the Hub class:<\/strong> Your ChatHub class needs to inherit from the SignalR <code>Hub<\/code> class, like so:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">ChatHub<\/span> : <span class=\"hljs-title\">Hub<\/span>\r\n{\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Define methods:<\/strong> Within this class, you can define public methods that can be called from a client connected to the hub. For our chat application, we&#8217;ll start by creating a method for sending messages to all clients:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">async<\/span> Task <span class=\"hljs-title\">SendMessage<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">string<\/span> user, <span class=\"hljs-keyword\">string<\/span> message<\/span>)<\/span>\r\n{\r\n    <span class=\"hljs-keyword\">await<\/span> Clients.All.SendAsync(<span class=\"hljs-string\">\"ReceiveMessage\"<\/span>, user, message);\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the code above, <code>SendMessage<\/code> is a server-side method that can be called from the client. When called, it uses the <code>Clients.All.SendAsync<\/code> method to call a client-side method named <code>ReceiveMessage<\/code> on all connected clients. The <code>ReceiveMessage<\/code> method will update the chat window with the new message.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You&#8217;ve now set up SignalR and created your first hub with a method for sending messages. We&#8217;ll expand on this as we proceed with building our chat application.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Designing the Front-End<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The front-end of our application is where users will interact with our chat service. We will use HTML and CSS to design the chat interface, and JavaScript\/jQuery to manage client-side interactions and communication with the server-side SignalR hub.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Designing the Chat UI with HTML &amp; CSS<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Our chat application will have a simple and intuitive user interface. The interface will have two main sections: a user list and a chat window. The user list will show all currently connected users, and the chat window will display messages from all users.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>HTML Structure:<\/strong><\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"HTML, XML\" data-shcb-language-slug=\"xml\"><span><code class=\"hljs language-xml\"><span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">div<\/span> <span class=\"hljs-attr\">class<\/span>=<span class=\"hljs-string\">\"container\"<\/span>&gt;<\/span>\n    <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">div<\/span> <span class=\"hljs-attr\">id<\/span>=<span class=\"hljs-string\">\"userContainer\"<\/span>&gt;<\/span>\n        <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">h2<\/span>&gt;<\/span>Users<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">h2<\/span>&gt;<\/span>\n        <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">ul<\/span> <span class=\"hljs-attr\">id<\/span>=<span class=\"hljs-string\">\"userList\"<\/span>&gt;<\/span><span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">ul<\/span>&gt;<\/span>\n    <span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">div<\/span>&gt;<\/span>\n\n    <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">div<\/span> <span class=\"hljs-attr\">id<\/span>=<span class=\"hljs-string\">\"chatContainer\"<\/span>&gt;<\/span>\n        <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">h2<\/span>&gt;<\/span>Chat<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">h2<\/span>&gt;<\/span>\n        <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">div<\/span> <span class=\"hljs-attr\">id<\/span>=<span class=\"hljs-string\">\"messageList\"<\/span>&gt;<\/span><span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">div<\/span>&gt;<\/span>\n        <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">textarea<\/span> <span class=\"hljs-attr\">id<\/span>=<span class=\"hljs-string\">\"messageInput\"<\/span>&gt;<\/span><span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">textarea<\/span>&gt;<\/span>\n        <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">button<\/span> <span class=\"hljs-attr\">id<\/span>=<span class=\"hljs-string\">\"sendButton\"<\/span>&gt;<\/span>Send<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">button<\/span>&gt;<\/span>\n    <span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">div<\/span>&gt;<\/span>\n<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">div<\/span>&gt;<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">HTML, XML<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">xml<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>CSS Styling:<\/strong><\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"CSS\" data-shcb-language-slug=\"css\"><span><code class=\"hljs language-css\"><span class=\"hljs-selector-class\">.container<\/span> {\n    <span class=\"hljs-attribute\">display<\/span>: flex;\n}\n\n<span class=\"hljs-selector-id\">#userContainer<\/span>, <span class=\"hljs-selector-id\">#chatContainer<\/span> {\n    <span class=\"hljs-attribute\">margin<\/span>: <span class=\"hljs-number\">10px<\/span>;\n    <span class=\"hljs-attribute\">padding<\/span>: <span class=\"hljs-number\">10px<\/span>;\n    <span class=\"hljs-attribute\">border<\/span>: <span class=\"hljs-number\">1px<\/span> solid <span class=\"hljs-number\">#ccc<\/span>;\n    <span class=\"hljs-attribute\">border-radius<\/span>: <span class=\"hljs-number\">5px<\/span>;\n}\n\n<span class=\"hljs-selector-id\">#messageList<\/span> {\n    <span class=\"hljs-attribute\">height<\/span>: <span class=\"hljs-number\">300px<\/span>;\n    <span class=\"hljs-attribute\">overflow-y<\/span>: auto;\n}\n\n<span class=\"hljs-selector-id\">#messageInput<\/span> {\n    <span class=\"hljs-attribute\">width<\/span>: <span class=\"hljs-number\">100%<\/span>;\n    <span class=\"hljs-attribute\">margin-top<\/span>: <span class=\"hljs-number\">10px<\/span>;\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">CSS<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">css<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">This basic setup creates a layout where the list of users is on the left and the chat area is on the right. The chat area has a scrolling area for messages and a text area for inputting new messages.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Incorporating JavaScript\/jQuery for Interactivity<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">We use JavaScript and jQuery to manage user interactions and real-time updates. We&#8217;ll need to establish a connection to the SignalR hub, handle the &#8216;send&#8217; button click event, and define the client-side method to display incoming messages.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>JavaScript Code:<\/strong><\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">$(<span class=\"hljs-built_in\">document<\/span>).ready(<span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span>(<span class=\"hljs-params\"><\/span>) <\/span>{\n    <span class=\"hljs-keyword\">const<\/span> connection = <span class=\"hljs-keyword\">new<\/span> signalR.HubConnectionBuilder().withUrl(<span class=\"hljs-string\">\"\/chatHub\"<\/span>).build();\n\n    connection.start().catch(<span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> (<span class=\"hljs-params\">err<\/span>) <\/span>{\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-built_in\">console<\/span>.error(err.toString());\n    });\n\n    connection.on(<span class=\"hljs-string\">\"ReceiveMessage\"<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> (<span class=\"hljs-params\">user, message<\/span>) <\/span>{\n        <span class=\"hljs-keyword\">const<\/span> messageEntry = <span class=\"hljs-string\">`&lt;div&gt;&lt;strong&gt;<span class=\"hljs-subst\">${user}<\/span>:&lt;\/strong&gt; <span class=\"hljs-subst\">${message}<\/span>&lt;\/div&gt;`<\/span>;\n        $(<span class=\"hljs-string\">'#messageList'<\/span>).append(messageEntry);\n    });\n\n    $(<span class=\"hljs-string\">\"#sendButton\"<\/span>).click(<span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> (<span class=\"hljs-params\">event<\/span>) <\/span>{\n        <span class=\"hljs-keyword\">const<\/span> user = <span class=\"hljs-string\">'User1'<\/span>; <span class=\"hljs-comment\">\/\/ Temporary static user. You could implement user input for this<\/span>\n        <span class=\"hljs-keyword\">const<\/span> message = $(<span class=\"hljs-string\">\"#messageInput\"<\/span>).val();\n        connection.invoke(<span class=\"hljs-string\">\"SendMessage\"<\/span>, user, message).catch(<span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> (<span class=\"hljs-params\">err<\/span>) <\/span>{\n            <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-built_in\">console<\/span>.error(err.toString());\n        });\n        event.preventDefault();\n    });\n});<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">This code starts a connection to the SignalR hub when the page loads, sets up an event handler for incoming messages, and sends messages to the server when the &#8216;send&#8217; button is clicked.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now we have a front-end interface where users can send messages and see messages from all users updated in real-time.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Implementing the Back-End<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The back-end of our application is responsible for accepting incoming connections, receiving messages from clients, and broadcasting these messages to all connected clients. For these functionalities, we will use C# along with SignalR to write our server-side code.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Writing C# Code for the Chat Server<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">To create our server-side logic, we&#8217;ll be extending our previously created <code>ChatHub<\/code>. Our chat server needs to manage connections, disconnections, and message broadcasting. Therefore, we&#8217;ll be implementing the following methods in the <code>ChatHub<\/code> class:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>OnConnectedAsync<\/code>: This method is executed when a new client connects. It&#8217;s a perfect place to notify other clients about the new user.<\/li>\n\n\n\n<li><code>OnDisconnectedAsync<\/code>: This method is executed when a client disconnects. We can use it to notify other clients that a user has left.<\/li>\n\n\n\n<li><code>SendMessage<\/code>: We&#8217;ve already defined this method, but we&#8217;ll need to adjust it to handle our user list.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s how the <code>ChatHub<\/code> class looks after implementing these methods:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">ChatHub<\/span> : <span class=\"hljs-title\">Hub<\/span>\n{\n    <span class=\"hljs-keyword\">static<\/span> HashSet&lt;<span class=\"hljs-keyword\">string<\/span>&gt; CurrentUsers = <span class=\"hljs-keyword\">new<\/span> HashSet&lt;<span class=\"hljs-keyword\">string<\/span>&gt;();\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">override<\/span> <span class=\"hljs-keyword\">async<\/span> Task <span class=\"hljs-title\">OnConnectedAsync<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>\n    {\n        <span class=\"hljs-keyword\">var<\/span> username = Context.ConnectionId;\n        CurrentUsers.Add(username);\n\n        <span class=\"hljs-comment\">\/\/ Notify the client about the new user<\/span>\n        <span class=\"hljs-keyword\">await<\/span> Clients.All.SendAsync(<span class=\"hljs-string\">\"NewUser\"<\/span>, username, CurrentUsers);\n\n        <span class=\"hljs-comment\">\/\/ Call the base method<\/span>\n        <span class=\"hljs-keyword\">await<\/span> <span class=\"hljs-keyword\">base<\/span>.OnConnectedAsync();\n    }\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">override<\/span> <span class=\"hljs-keyword\">async<\/span> Task <span class=\"hljs-title\">OnDisconnectedAsync<\/span>(<span class=\"hljs-params\">Exception exception<\/span>)<\/span>\n    {\n        <span class=\"hljs-keyword\">var<\/span> username = Context.ConnectionId;\n        CurrentUsers.Remove(username);\n\n        <span class=\"hljs-comment\">\/\/ Notify the client about the disconnected user<\/span>\n        <span class=\"hljs-keyword\">await<\/span> Clients.All.SendAsync(<span class=\"hljs-string\">\"UserDisconnected\"<\/span>, username, CurrentUsers);\n\n        <span class=\"hljs-comment\">\/\/ Call the base method<\/span>\n        <span class=\"hljs-keyword\">await<\/span> <span class=\"hljs-keyword\">base<\/span>.OnDisconnectedAsync(exception);\n    }\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">async<\/span> Task <span class=\"hljs-title\">SendMessage<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">string<\/span> message<\/span>)<\/span>\n    {\n        <span class=\"hljs-keyword\">var<\/span> username = Context.ConnectionId;\n        <span class=\"hljs-keyword\">await<\/span> Clients.All.SendAsync(<span class=\"hljs-string\">\"ReceiveMessage\"<\/span>, username, message);\n    }\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the code above, <code>CurrentUsers<\/code> is a HashSet that keeps track of all connected users. We add a user when a new connection is established and remove a user when a connection is closed.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Creating SignalR Methods<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">In addition to server-side methods, SignalR also allows us to define client-side methods that the server can call. We have already defined the <code>ReceiveMessage<\/code> method in the JavaScript code. Now, we will need to define two more methods to handle new users and disconnected users. This can be done by extending our previous JavaScript code:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-comment\">\/\/ ...<\/span>\n\nconnection.on(<span class=\"hljs-string\">\"NewUser\"<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> (<span class=\"hljs-params\">username, userList<\/span>) <\/span>{\n    <span class=\"hljs-comment\">\/\/ Code to update the user list and notify about the new user<\/span>\n});\n\nconnection.on(<span class=\"hljs-string\">\"UserDisconnected\"<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> (<span class=\"hljs-params\">username, userList<\/span>) <\/span>{\n    <span class=\"hljs-comment\">\/\/ Code to update the user list and notify about the disconnected user<\/span>\n});\n\n<span class=\"hljs-comment\">\/\/ ...<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the <code>NewUser<\/code> and <code>UserDisconnected<\/code> methods, you will need to write code to update the user list displayed on the page and possibly display a notification about the new or disconnected user.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Establishing a Connection with SignalR<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The SignalR JavaScript library enables easy communication between the client-side JavaScript and server-side C#. It provides an API for creating and managing a SignalR connection to the server. Let&#8217;s discuss how we can use this library to establish a connection to the SignalR Hub.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Using SignalR JavaScript Library<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Before we can use SignalR in our JavaScript code, we need to ensure that the SignalR library is available on our webpage. This can be done by including a <code>&lt;script&gt;<\/code> tag pointing to the SignalR JavaScript library in our HTML file.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We can use the version hosted by Microsoft&#8217;s CDN:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"HTML, XML\" data-shcb-language-slug=\"xml\"><span><code class=\"hljs language-xml\"><span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">script<\/span> <span class=\"hljs-attr\">src<\/span>=<span class=\"hljs-string\">\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/microsoft-signalr\/5.0.8\/signalr.min.js\"<\/span>&gt;<\/span><span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">script<\/span>&gt;<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">HTML, XML<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">xml<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Make sure this line comes before your own JavaScript file in the HTML so that the SignalR library is loaded first.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Establishing the Connection to the Hub<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Once we have the SignalR library available, we can create a connection to our SignalR hub. This can be done using the <code>signalR.HubConnectionBuilder().withUrl(\"\/yourhubpath\").build()<\/code> method provided by the SignalR library:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">const<\/span> connection = <span class=\"hljs-keyword\">new<\/span> signalR.HubConnectionBuilder().withUrl(<span class=\"hljs-string\">\"\/chatHub\"<\/span>).build();<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the above line, replace &#8220;\/chatHub&#8221; with the path to your hub that you defined in the Startup.cs file.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">After we have built our connection, we start it using the <code>start()<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">connection.start().catch(<span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> (<span class=\"hljs-params\">err<\/span>) <\/span>{\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-built_in\">console<\/span>.error(err.toString());\n});<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The <code>start()<\/code> method returns a Promise and hence, it&#8217;s a good idea to handle any potential errors using a <code>catch()<\/code> clause.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Once the connection is established, the client can send messages to the server using the <code>invoke()<\/code> method and register functions that can be called by the server using the <code>on()<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-15\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">connection.invoke(<span class=\"hljs-string\">\"SendMessage\"<\/span>, user, message).catch(<span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> (<span class=\"hljs-params\">err<\/span>) <\/span>{\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-built_in\">console<\/span>.error(err.toString());\n});\n\nconnection.on(<span class=\"hljs-string\">\"ReceiveMessage\"<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> (<span class=\"hljs-params\">user, message<\/span>) <\/span>{\n    <span class=\"hljs-comment\">\/\/ Code to handle the incoming message<\/span>\n});<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-15\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the above code, <code>SendMessage<\/code> is the server-side method that we are calling to send a new message, and <code>ReceiveMessage<\/code> is the client-side method that the server will call to update the chat window with a new message.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">With this, we&#8217;ve successfully established a connection to our SignalR hub, enabling real-time communication between the client and server. This will allow our chat application to update the chat window in real-time as new messages arrive.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Sending and Receiving Messages<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To implement the core functionality of our chat application, we need to set up the processes for sending and receiving messages. This involves writing server-side C# code to broadcast messages and client-side JavaScript code to receive and display the messages.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Writing C# Code for Sending Messages<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">In our <code>ChatHub<\/code> class, we&#8217;ve already written a method named <code>SendMessage<\/code> for sending messages. This method takes in the message text and broadcasts it to all connected clients:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-16\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">async<\/span> Task <span class=\"hljs-title\">SendMessage<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">string<\/span> message<\/span>)<\/span>\n{\n    <span class=\"hljs-keyword\">var<\/span> username = Context.ConnectionId;\n    <span class=\"hljs-keyword\">await<\/span> Clients.All.SendAsync(<span class=\"hljs-string\">\"ReceiveMessage\"<\/span>, username, message);\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-16\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The <code>Clients.All.SendAsync<\/code> method is used to call a client-side method (<code>ReceiveMessage<\/code>) on all connected clients. <code>username<\/code> and <code>message<\/code> are the parameters that are passed to the client-side method.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Writing JavaScript Code for Receiving and Displaying Messages<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">In the client-side JavaScript, we define the <code>ReceiveMessage<\/code> method that the server will call to send a new message. This method updates the chat window with the new message:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-17\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">connection.on(<span class=\"hljs-string\">\"ReceiveMessage\"<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> (<span class=\"hljs-params\">username, message<\/span>) <\/span>{\n    <span class=\"hljs-keyword\">const<\/span> messageEntry = <span class=\"hljs-string\">`&lt;div&gt;&lt;strong&gt;<span class=\"hljs-subst\">${username}<\/span>:&lt;\/strong&gt; <span class=\"hljs-subst\">${message}<\/span>&lt;\/div&gt;`<\/span>;\n    $(<span class=\"hljs-string\">'#messageList'<\/span>).append(messageEntry);\n});<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-17\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The <code>connection.on<\/code> function is used to define a method that the server can call. The method takes two parameters (<code>username<\/code> and <code>message<\/code>) that match the parameters sent by the server-side <code>SendMessage<\/code> method.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>messageEntry<\/code> is a string containing HTML markup that represents a new message in the chat window. It is appended to the <code>messageList<\/code> element which is the container for all chat messages.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Additionally, we&#8217;ll need code to handle the sending of new messages. Here&#8217;s how we could handle the &#8216;Send&#8217; button click event:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-18\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">$(<span class=\"hljs-string\">\"#sendButton\"<\/span>).click(<span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> (<span class=\"hljs-params\">event<\/span>) <\/span>{\n    <span class=\"hljs-keyword\">const<\/span> user = <span class=\"hljs-string\">'User1'<\/span>; <span class=\"hljs-comment\">\/\/ Temporary static user. You could implement user input for this<\/span>\n    <span class=\"hljs-keyword\">const<\/span> message = $(<span class=\"hljs-string\">\"#messageInput\"<\/span>).val();\n    connection.invoke(<span class=\"hljs-string\">\"SendMessage\"<\/span>, message).catch(<span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> (<span class=\"hljs-params\">err<\/span>) <\/span>{\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-built_in\">console<\/span>.error(err.toString());\n    });\n    event.preventDefault();\n});<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-18\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In this code, we get the user input from the <code>messageInput<\/code> element and send it to the server by calling the <code>SendMessage<\/code> method. The <code>connection.invoke<\/code> function is used to call server-side methods from the client.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">With this setup, our application can send and receive messages in real time, which forms the core functionality of our chat application.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Testing the Application<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">After setting up our chat application, it&#8217;s time to test it to ensure it&#8217;s working as expected. This involves running the server and testing the real-time chat functionality using multiple browsers or browser tabs.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Running the Server<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">To start the server, navigate to the project directory in the command prompt or terminal and run the following command:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-19\" data-shcb-language-name=\"Bash\" data-shcb-language-slug=\"bash\"><span><code class=\"hljs language-bash\">dotnet run<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-19\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Bash<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">bash<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">This command will build and run your application. If your application is set up correctly, you should see output indicating that your server is running and listening for connections. The output will include a URL, usually <code>http:\/\/localhost:5000<\/code> or <code>https:\/\/localhost:5001<\/code>, where your application can be accessed.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Opening Multiple Browsers to Test Real-Time Chat<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">To test the real-time chat functionality of the application, open your browser and navigate to the URL provided in the server output. Remember to append the path to your chat page if it&#8217;s not the index page, for example, <code>http:\/\/localhost:5000\/chat<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To simulate multiple users, you can open your application in multiple browsers or browser tabs. Then, try sending a message from one tab and verify that the message appears in all other tabs in real-time. You should also test the user list update functionality by connecting and disconnecting users.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Remember to check the console of your browsers for any potential JavaScript errors and your server&#8217;s terminal window for any server-side exceptions. Debugging these errors will give you valuable insight into any issues that may exist in your application.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Once your chat application is working as expected in your local environment, it&#8217;s ready to be deployed or extended with additional features.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Enhancements and Features<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The basic chat application that we&#8217;ve built is a great starting point, but there are many features and enhancements that could be added to make it more robust and user-friendly. Here are a few suggestions for additional features you could implement:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Implementing User Authentication<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Currently, our application does not distinguish between different users. Adding user authentication could allow users to have unique usernames and potentially profiles. This would involve setting up a user database and incorporating login and signup functionality into the front-end. On the server-side, the <code>Context.ConnectionId<\/code> could be replaced with the username of the authenticated user.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Allowing Private Messages<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Currently, all messages are broadcast to all users. It would be great to add the ability for users to send private messages to each other. This could be implemented by adding a <code>SendPrivateMessage<\/code> method to the <code>ChatHub<\/code> class, which would use the <code>Clients.Client(connectionId).SendAsync<\/code> method to send a message to a specific client.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Adding User is Typing Indicator<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A &#8220;user is typing&#8221; indicator can provide real-time feedback to users about the activity of other users. This could be achieved by sending a message to the server whenever a user starts typing and broadcasting this event to other clients. The typing status could be displayed next to the user&#8217;s name in the user list.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Message History Retrieval<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The ability to retrieve and display a history of messages can be a useful feature for a chat application. This could be achieved by storing all messages in a database and retrieving them whenever a new user connects or a user reloads the page. The retrieved messages could be sent to the client and appended to the chat window.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common Issues and Their Resolutions<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Building a real-time chat application with SignalR and C# can present a few challenges. Here are some common issues you may encounter and potential solutions for them:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">List of Potential Issues Faced<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Failed to start SignalR connection:<\/strong> You may run into issues where your SignalR connection fails to start. This could be due to an incorrect URL or a problem with your SignalR Hub configuration.<\/li>\n\n\n\n<li><strong>Error messages are not being sent or received:<\/strong> If your messages are not being sent or received, it could be due to a problem with your <code>SendMessage<\/code> or <code>ReceiveMessage<\/code> methods, or there could be an issue with how you&#8217;re invoking these methods.<\/li>\n\n\n\n<li><strong>JavaScript errors in the browser console:<\/strong> You may see various JavaScript errors in your browser&#8217;s console. These could be due to a syntax error, a problem with your SignalR JavaScript library, or an issue with your JavaScript code that interacts with the SignalR connection.<\/li>\n\n\n\n<li><strong>SignalR falling back to long polling:<\/strong> While SignalR will try to use WebSockets by default, it may fall back to long polling in certain circumstances, which can result in less efficient communication.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Debugging and Solutions<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Failed to start SignalR connection:<\/strong> Make sure you&#8217;ve correctly defined your Hub in your Startup.cs file and that the URL in your JavaScript matches this definition. Also, ensure that you&#8217;ve correctly included the SignalR JavaScript library in your HTML file.<\/li>\n\n\n\n<li><strong>Error messages are not being sent or received:<\/strong> Check that your <code>SendMessage<\/code> method is correctly broadcasting the message to all clients, and that your <code>ReceiveMessage<\/code> method is correctly handling the incoming messages. Ensure that you&#8217;re correctly invoking these methods in your JavaScript code.<\/li>\n\n\n\n<li><strong>JavaScript errors in the browser console:<\/strong> For syntax errors, carefully review your code to ensure it&#8217;s syntactically correct. If there&#8217;s an issue with the SignalR JavaScript library, ensure you&#8217;ve correctly included it in your HTML file, and that it&#8217;s loading before your own JavaScript file. For issues with your SignalR JavaScript code, ensure that you&#8217;re correctly creating the SignalR connection and invoking your Hub methods.<\/li>\n\n\n\n<li><strong>SignalR falling back to long polling:<\/strong> SignalR uses a technique called transport negotiation to determine the best way to communicate with the server. If SignalR is falling back to long polling, it may be because WebSockets are not enabled in your server configuration, or your client or network does not support it. Check your server configuration to ensure that WebSockets are enabled and that you&#8217;re not blocking WebSockets in your network.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">SignalR opens up a wide range of possibilities for creating real-time, interactive web applications. Beyond chat applications, you can use SignalR in any scenario that requires high-frequency updates from the server, such as live gaming, real-time monitoring, collaborative apps, and more.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction Real-time communication has become a fundamental part of the digital world. Whether it&#8217;s instant messaging, live video streaming, or multiplayer online games, real-time communication delivers instantaneous, bidirectional communication between users over the internet. This enables interactions that are as close as possible to face-to-face communication, but with the flexibility and convenience of digital. In [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_genesis_hide_title":false,"_genesis_hide_breadcrumbs":false,"_genesis_hide_singular_image":false,"_genesis_hide_footer_widgets":false,"_genesis_custom_body_class":"","_genesis_custom_post_class":"","_genesis_layout":"","_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[8,4],"tags":[],"class_list":["post-794","post","type-post","status-publish","format-standard","category-csharp","category-programming-languages","entry"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.6 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Build a Real-Time Chat Application with SignalR in C#<\/title>\n<meta name=\"description\" content=\"SignalR, a software library for Microsoft .NET, plays a critical role in enabling real-time communication. It simplifies the process of adding\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.w3computing.com\/articles\/real-time-chat-application-signalr-csharp\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Build a Real-Time Chat Application with SignalR in C#\" \/>\n<meta property=\"og:description\" content=\"SignalR, a software library for Microsoft .NET, plays a critical role in enabling real-time communication. It simplifies the process of adding\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.w3computing.com\/articles\/real-time-chat-application-signalr-csharp\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-08-04T01:15:04+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-08-23T16:20:28+00:00\" \/>\n<meta name=\"author\" content=\"w3compadmin\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"w3compadmin\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"20 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"TechArticle\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/real-time-chat-application-signalr-csharp\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/real-time-chat-application-signalr-csharp\\\/\"},\"author\":{\"name\":\"w3compadmin\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#\\\/schema\\\/person\\\/a550b3e20d78bb4f79b7c6b7b53f0561\"},\"headline\":\"Build a Real-Time Chat Application with SignalR in C#\",\"datePublished\":\"2023-08-04T01:15:04+00:00\",\"dateModified\":\"2023-08-23T16:20:28+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/real-time-chat-application-signalr-csharp\\\/\"},\"wordCount\":4446,\"commentCount\":0,\"articleSection\":[\"C#\",\"Programming Languages\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/real-time-chat-application-signalr-csharp\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/real-time-chat-application-signalr-csharp\\\/\",\"url\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/real-time-chat-application-signalr-csharp\\\/\",\"name\":\"Build a Real-Time Chat Application with SignalR in C#\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#website\"},\"datePublished\":\"2023-08-04T01:15:04+00:00\",\"dateModified\":\"2023-08-23T16:20:28+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#\\\/schema\\\/person\\\/a550b3e20d78bb4f79b7c6b7b53f0561\"},\"description\":\"SignalR, a software library for Microsoft .NET, plays a critical role in enabling real-time communication. It simplifies the process of adding\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/real-time-chat-application-signalr-csharp\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/real-time-chat-application-signalr-csharp\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/real-time-chat-application-signalr-csharp\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Articles Home\",\"item\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Programming Languages\",\"item\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/programming-languages\\\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Build a Real-Time Chat Application with SignalR in C#\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#website\",\"url\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/\",\"name\":\"Developer Articles Hub\",\"description\":\"\",\"alternateName\":\"Developer Articles\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#\\\/schema\\\/person\\\/a550b3e20d78bb4f79b7c6b7b53f0561\",\"name\":\"w3compadmin\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/wp-content\\\/litespeed\\\/avatar\\\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266\",\"url\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/wp-content\\\/litespeed\\\/avatar\\\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266\",\"contentUrl\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/wp-content\\\/litespeed\\\/avatar\\\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266\",\"caption\":\"w3compadmin\"},\"sameAs\":[\"http:\\\/\\\/w3computing.com\\\/articles\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Build a Real-Time Chat Application with SignalR in C#","description":"SignalR, a software library for Microsoft .NET, plays a critical role in enabling real-time communication. It simplifies the process of adding","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.w3computing.com\/articles\/real-time-chat-application-signalr-csharp\/","og_locale":"en_US","og_type":"article","og_title":"Build a Real-Time Chat Application with SignalR in C#","og_description":"SignalR, a software library for Microsoft .NET, plays a critical role in enabling real-time communication. It simplifies the process of adding","og_url":"https:\/\/www.w3computing.com\/articles\/real-time-chat-application-signalr-csharp\/","article_published_time":"2023-08-04T01:15:04+00:00","article_modified_time":"2023-08-23T16:20:28+00:00","author":"w3compadmin","twitter_card":"summary_large_image","twitter_misc":{"Written by":"w3compadmin","Est. reading time":"20 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"TechArticle","@id":"https:\/\/www.w3computing.com\/articles\/real-time-chat-application-signalr-csharp\/#article","isPartOf":{"@id":"https:\/\/www.w3computing.com\/articles\/real-time-chat-application-signalr-csharp\/"},"author":{"name":"w3compadmin","@id":"https:\/\/www.w3computing.com\/articles\/#\/schema\/person\/a550b3e20d78bb4f79b7c6b7b53f0561"},"headline":"Build a Real-Time Chat Application with SignalR in C#","datePublished":"2023-08-04T01:15:04+00:00","dateModified":"2023-08-23T16:20:28+00:00","mainEntityOfPage":{"@id":"https:\/\/www.w3computing.com\/articles\/real-time-chat-application-signalr-csharp\/"},"wordCount":4446,"commentCount":0,"articleSection":["C#","Programming Languages"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.w3computing.com\/articles\/real-time-chat-application-signalr-csharp\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.w3computing.com\/articles\/real-time-chat-application-signalr-csharp\/","url":"https:\/\/www.w3computing.com\/articles\/real-time-chat-application-signalr-csharp\/","name":"Build a Real-Time Chat Application with SignalR in C#","isPartOf":{"@id":"https:\/\/www.w3computing.com\/articles\/#website"},"datePublished":"2023-08-04T01:15:04+00:00","dateModified":"2023-08-23T16:20:28+00:00","author":{"@id":"https:\/\/www.w3computing.com\/articles\/#\/schema\/person\/a550b3e20d78bb4f79b7c6b7b53f0561"},"description":"SignalR, a software library for Microsoft .NET, plays a critical role in enabling real-time communication. It simplifies the process of adding","breadcrumb":{"@id":"https:\/\/www.w3computing.com\/articles\/real-time-chat-application-signalr-csharp\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.w3computing.com\/articles\/real-time-chat-application-signalr-csharp\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.w3computing.com\/articles\/real-time-chat-application-signalr-csharp\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Articles Home","item":"https:\/\/www.w3computing.com\/articles\/"},{"@type":"ListItem","position":2,"name":"Programming Languages","item":"https:\/\/www.w3computing.com\/articles\/programming-languages\/"},{"@type":"ListItem","position":3,"name":"Build a Real-Time Chat Application with SignalR in C#"}]},{"@type":"WebSite","@id":"https:\/\/www.w3computing.com\/articles\/#website","url":"https:\/\/www.w3computing.com\/articles\/","name":"Developer Articles Hub","description":"","alternateName":"Developer Articles","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.w3computing.com\/articles\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/www.w3computing.com\/articles\/#\/schema\/person\/a550b3e20d78bb4f79b7c6b7b53f0561","name":"w3compadmin","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.w3computing.com\/articles\/wp-content\/litespeed\/avatar\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266","url":"https:\/\/www.w3computing.com\/articles\/wp-content\/litespeed\/avatar\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266","contentUrl":"https:\/\/www.w3computing.com\/articles\/wp-content\/litespeed\/avatar\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266","caption":"w3compadmin"},"sameAs":["http:\/\/w3computing.com\/articles"]}]}},"featured_image_src":null,"featured_image_src_square":null,"author_info":{"display_name":"w3compadmin","author_link":"https:\/\/www.w3computing.com\/articles\/author\/w3compadmin\/"},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts\/794","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/comments?post=794"}],"version-history":[{"count":8,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts\/794\/revisions"}],"predecessor-version":[{"id":802,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts\/794\/revisions\/802"}],"wp:attachment":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/media?parent=794"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/categories?post=794"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/tags?post=794"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}