Home   dotnet  

SignalR library in ASP.NET

SignalR is a library for ASP.NET that simplifies the process of adding real-time web functionality to applications. Real-time web functionality allows server-side code to push content to clients instantly, rather than having the server wait for a client to request new data.

Key Features of SignalR

  1. Real-Time Communication: Enables real-time bi-directional communication between server and client.
  2. Persistent Connections: Uses WebSockets as the underlying protocol when available and falls back to other techniques like Server-Sent Events (SSE) or Long Polling when necessary.
  3. Automatic Reconnection: Automatically reconnects clients that are temporarily disconnected.
  4. Scalability: Can be scaled out using the Redis, SQL Server, or Azure Service Bus backplanes.
  5. Client Libraries: Supports multiple client platforms, including JavaScript for web applications, .NET clients, and even mobile platforms.

How SignalR Works

SignalR uses a concept called "Hubs" to establish a communication channel between the client and the server. Hubs are high-level pipelines that allow the client and server to call methods on each other directly.

Example Usage of SignalR

Server-Side (ASP.NET Core)

  1. Install SignalR Package:

    dotnet add package Microsoft.AspNetCore.SignalR
    
  2. Create a Hub Class:

    using Microsoft.AspNetCore.SignalR;
    
    public class ChatHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
    
  3. Configure SignalR in Startup.cs:

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSignalR();
            services.AddControllersWithViews();
        }
    
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
    
            app.UseHttpsRedirection();
            app.UseStaticFiles();
    
            app.UseRouting();
    
            app.UseAuthorization();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<ChatHub>("/chathub");
            });
        }
    }
    

Client-Side (JavaScript)

  1. Add SignalR Client Library:

    Include the SignalR client library in your HTML file.

    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/3.1.7/signalr.min.js"></script>
    
  2. Connect to the Hub and Send/Receive Messages:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Chat</title>
    </head>
    <body>
        <div>
            <input type="text" id="userInput" placeholder="Name" />
            <input type="text" id="messageInput" placeholder="Message" />
            <button onclick="sendMessage()">Send</button>
        </div>
        <ul id="messagesList"></ul>
    
        <script>
            const connection = new signalR.HubConnectionBuilder()
                .withUrl("/chathub")
                .build();
    
            connection.on("ReceiveMessage", (user, message) => {
                const li = document.createElement("li");
                li.textContent = `${user}: ${message}`;
                document.getElementById("messagesList").appendChild(li);
            });
    
            connection.start().catch(err => console.error(err.toString()));
    
            function sendMessage() {
                const user = document.getElementById("userInput").value;
                const message = document.getElementById("messageInput").value;
                connection.invoke("SendMessage", user, message).catch(err => console.error(err.toString()));
            }
        </script>
    </body>
    </html>
    

Use Cases for SignalR

Published on: Jul 06, 2024, 07:02 AM  
 

Comments

Add your comment