SignalR will Allow Clients and Servers to Communicate in Real Time

SignalR allows clients and servers to communicate in real-time. SignalR is an ASP.NET library that allows you to create real-time, interactive online apps. In this example, we’ll build a simple chat application that allows users to send and receive messages in real-time. To follow this example, you must have ASP.NET Core installed and start a new ASP.NET Core web application.

Make a fresh ASP.NET Core Web Application.

Start Visual Studio and make a new web project called SignalRChatApp. Run the following commands from your command prompt or terminal.

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 looked at how to use SignalR in an ASP.NET Core web application to enable real-time communication between clients and a server. We’ve shown how to set up a SignalR hub, configure SignalR in the Startup class, create a chat UI, and handle real-time communications between clients by constructing a simple chat application as an example. This example lays the groundwork for more complicated real-time applications and demonstrates the ability of SignalR in improving user experiences through instant, interactive communication.

Best ASP.NET Core Hosting

The feature and reliability are the most important things when choosing a good ASP.NET Core hosting. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core , their servers are optimized for PHP web applications such as the latest ASP.NET Core version. The performance and the uptime of the ASP.NET Core  hosting service are excellent, and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. At HostForLIFEASP.NET, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its data centers are equipped with top equipment like cooling system, fire detection, high-speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core . And the engineers do regular maintenance and monitoring works to assure its ASP.NET Core  hosting are security and always up.

hostforlifebanner