SignalR With ASP.NET Core Hosted Service .NET 5

Introduction

What is SignalR?

The SignalR is a real-time communication library developed by Microsoft that enables bi-directional communication between clients (such as web browsers, mobile devices, or backend services) and a server. It allows for building interactive and dynamic web applications that can push data from the server to connected clients instantly, creating a real-time and responsive user experience.

Key features and concepts of SignalR include:

  1. Real-Time Communication: SignalR enables real-time communication between clients and servers, allowing data to be pushed from the server to connected clients as soon as it becomes available.
  2. WebSockets and Fallbacks: SignalR uses WebSockets as the primary transport mechanism for real-time communication when supported by the client and server. For environments where WebSockets are not available or supported, SignalR falls back to other transport methods such as Server-Sent Events (SSE) or long polling.
  3. Hubs: SignalR provides a high-level abstraction called “hubs” that allow developers to define methods on the server that can be called by clients, and vice versa. Hubs simplify the process of managing client-server communication and provide a structured way to send messages.
  4. Groups: SignalR allows clients to be organized into groups, making it easy to send messages to specific subsets of connected clients. Groups are particularly useful for scenarios such as broadcasting messages to users in a specific chat room.
  5. Persistent Connections: SignalR supports persistent connections, which allow clients to maintain a long-lived connection to the server. This enables efficient communication without the need for frequent polling.
  6. Cross-Platform: SignalR is available for multiple platforms, including .NET Framework, .NET Core, and JavaScript. This makes it possible to create real-time applications that work across different environments.
  7. Scalability: SignalR supports scaling out to handle a large number of clients by distributing connections across multiple servers or instances.
  8. Use Cases: SignalR is used in various applications, such as real-time dashboards, collaborative applications, online gaming, chat applications, live data updates, notifications, and more.

SignalR has become an essential tool for building modern web applications that require real-time communication and interaction. It abstracts the complexities of low-level networking and provides a straightforward way to implement real-time features without requiring developers to manage the underlying infrastructure. Whether it’s updating a live dashboard, notifying users of events, or facilitating real-time collaboration, SignalR empowers developers to create dynamic and engaging experiences for users.

Certainly! Here’s an example of how to use SignalR with an ASP.NET Core hosted service in .NET 6. In this example, we’ll create a simple real-time chat application using SignalR and a background hosted service.

  1. Create a New ASP.NET Core Web Application:
    Open a terminal and run the following command to create a new ASP.NET Core web application:
   dotnet new web -n SignalRChatApp
   cd SignalRChatApp
  1. Install SignalR NuGet Package:
    Install the SignalR package for the project:
   dotnet add package Microsoft.AspNetCore.SignalR
  1. Create a ChatHub:
    Create a new SignalR hub called ChatHub.cs in the Hubs folder:
   using Microsoft.AspNetCore.SignalR;
   using System.Threading.Tasks;

   namespace SignalRChatApp.Hubs
   {
       public class ChatHub : Hub
       {
           public async Task SendMessage(string user, string message)
           {
               await Clients.All.SendAsync("ReceiveMessage", user, message);
           }
       }
   }
  1. Configure SignalR in Startup.cs:
    In the Startup.cs file, configure SignalR services:
   using SignalRChatApp.Hubs;

   public void ConfigureServices(IServiceCollection services)
   {
       // ...
       services.AddSignalR();
       // ...
   }
  1. Create a Hosted Service:
    Create a hosted service to send a random message to the clients every few seconds. Create a new class named RandomMessageHostedService.cs:
   using Microsoft.AspNetCore.SignalR;
   using Microsoft.Extensions.Hosting;
   using System;
   using System.Threading;
   using System.Threading.Tasks;

   namespace SignalRChatApp
   {
       public class RandomMessageHostedService : BackgroundService
       {
           private readonly IHubContext<ChatHub> _hubContext;
           private readonly Random _random;

           public RandomMessageHostedService(IHubContext<ChatHub> hubContext)
           {
               _hubContext = hubContext;
               _random = new Random();
           }

           protected override async Task ExecuteAsync(CancellationToken stoppingToken)
           {
               while (!stoppingToken.IsCancellationRequested)
               {
                   var user = "Server";
                   var message = $"Random message: {Guid.NewGuid()}";
                   await _hubContext.Clients.All.SendAsync("ReceiveMessage", user, message);
                   await Task.Delay(TimeSpan.FromSeconds(_random.Next(5, 15)), stoppingToken);
               }
           }
       }
   }
  1. Register the Hosted Service in Startup.cs:
    In the Startup.cs file, add the hosted service to the services collection:
   using Microsoft.Extensions.DependencyInjection;

   public void ConfigureServices(IServiceCollection services)
   {
       // ...
       services.AddHostedService<RandomMessageHostedService>();
       // ...
   }
  1. Update Index.cshtml for SignalR:
    Update the Views/Home/Index.cshtml file to include SignalR JavaScript code:
   <h1>SignalR Chat</h1>

   <div id="messages"></div>

   <input type="text" id="userInput" placeholder="User" />
   <input type="text" id="messageInput" placeholder="Message" />
   <button id="sendButton">Send</button>

   <script src="~/lib/microsoft/signalr/dist/browser/signalr.min.js"></script>
   <script>
       var connection = new signalR.HubConnectionBuilder().withUrl("/chathub").build();

       connection.on("ReceiveMessage", function (user, message) {
           var encodedMsg = user + " says: " + message;
           var li = document.createElement("li");
           li.textContent = encodedMsg;
           document.getElementById("messages").appendChild(li);
       });

       connection.start().catch(function (err) {
           return console.error(err.toString());
       });

       document.getElementById("sendButton").addEventListener("click", function (event) {
           var user = document.getElementById("userInput").value;
           var message = document.getElementById("messageInput").value;
           connection.invoke("SendMessage", user, message).catch(function (err) {
               return console.error(err.toString());
           });
           event.preventDefault();
       });
   </script>
  1. Run the Application:
    Run the application using the following command:
   dotnet run

Open a web browser and navigate to https://localhost:5001 to see the chat application in action. You should see messages from the background hosted service and be able to send messages from the browser.

This example demonstrates how to use SignalR with an ASP.NET Core hosted service to create a real-time chat application. The hosted service sends random messages to clients using SignalR. You can extend this example by adding more features to the chat application or customizing the behavior of the hosted service.

Leave a Reply

Your email address will not be published. Required fields are marked *