SignalR to enable real-time communication between clients and the server

SignalR to enable real-time communication between clients and a server. SignalR is a library for ASP.NET that allows you to build real-time, interactive web applications. In this example, we'll create a simple chat application where clients can send and receive messages in real-time.

Please note that you'll need to have ASP.NET Core installed and create a new ASP.NET Core web application to follow this example.

Create a new ASP.NET Core Web Application

Open the Visual Studio and create a new web project named SignalRChatApp OR Open your command prompt or terminal and run the following commands.

dotnet new web -n SignalRChatApp
cd SignalRChatApp

Here, I am using ASP.NET Core 5.

Install SignalR package

Run the following command to add the SignalR package to your project:

dotnet add package Microsoft.AspNetCore.SignalR

Create a ChatHub class

In your project folder, create a class named ChatHub.cs in the Hubs folder (you may need to create 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);
        }
    }
}

Configure SignalR in Startup.cs

In the Startup.cs file, configure SignalR services in the ConfigureServices method, and add the SignalR hub in the Configure method:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using SignalRChatApp.Hubs;

public class Startup
{
    // ...

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSignalR();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // ...

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapHub<ChatHub>("/chatHub"); // Map the ChatHub to a URL endpoint
        });
    }
}

Create a simple Razor Page for the chat UI

In the Pages folder, create a new Razor Page named Chat.cshtml:

@page
<div>
    <input id="userInput" type="text" placeholder="Enter your name" />
    <input id="messageInput" type="text" placeholder="Enter your message" />
    <button id="sendButton">Send</button>
</div>
<Hi>Hi Here is Complete Example Of SignalR By Sardar Mudassar Ali Khan</Hi>
<ul id="messagesList"></ul>
<script src="~/lib/microsoft/signalr/dist/browser/signalr.min.js"></script>
<script>
    const userInput = document.getElementById("userInput");
    const messageInput = document.getElementById("messageInput");
    const sendButton = document.getElementById("sendButton");
    const messagesList = document.getElementById("messagesList");

    const connection = new signalR.HubConnectionBuilder()
        .withUrl("/chatHub")
        .build();

    connection.start().catch(err => console.error(err.toString()));

    connection.on("ReceiveMessage", (user, message) => {
        const listItem = document.createElement("li");
        listItem.textContent = `${user}: ${message}`;
        messagesList.appendChild(listItem);
    });

    sendButton.addEventListener("click", () => {
        const user = userInput.value;
        const message = messageInput.value;
        connection.invoke("SendMessage", user, message).catch(err => console.error(err.toString()));
        messageInput.value = "";
    });
</script>

Run the application

Run the application using Visual Studio OR Run the following command in your project directory to start the application:

dotnet run

Conclusion

We've explored how to use SignalR to enable real-time communication between clients and a server in an ASP.NET Core web application. By creating a simple chat application as an example, we've demonstrated the key steps involved, including setting up a SignalR hub, configuring SignalR in the Startup class, creating a chat UI, and handling real-time messaging between clients. This example provides a foundation for building more complex real-time applications and showcases the power of SignalR in enhancing user experiences by enabling instant, interactive communication.