Advertisement
Поиск  
Always will be ready notify the world about expectations as easy as possible: job change page
Mar 12, 2023

Real-time communication with SignalR in .NET Core

Автор:
Ibrahim Jaber
Источник:
Просмотров:
2464

Introduction: In today’s world, real-time communication is essential for many web applications. For example, consider an online game where players need to communicate with each other in real-time, or a chat application where users expect instant messaging. Fortunately, SignalR, a real-time web framework, is available to help developers implement such functionalities in their web applications.

In this blog, we will explore how to use SignalR in .NET Core to implement real-time communication. We will create a simple chat application where users can send and receive messages in real-time. Let’s get started!

Step 1: Create a new .NET Core project

Open Visual Studio and create a new .NET Core project. Select “ASP.NET Core Web Application” and give your project a name. Choose the “API” template and click “Create”.

Step 2: Install the SignalR package

Next, we need to install the SignalR package in our project. Open the NuGet Package Manager and search for “Microsoft.AspNetCore.SignalR”. Install the latest version of the package.

Step 3: Add a SignalR hub

A SignalR hub is a class that manages real-time communication between clients and the server. We need to create a new hub for our chat application.

Create a new folder called “Hubs” in your project and add a new class called “ChatHub.cs”. This class will inherit from the “Hub” class provided by the SignalR package.

using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

namespace YourProjectName.Hubs
{
    public class ChatHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
}

This code defines a method called “SendMessage” that takes two parameters: the name of the user who sent the message and the message itself. It then calls the “SendAsync” method to send the message to all connected clients, passing in the name of the method (“ReceiveMessage”) and the parameters to be sent.

Step 4: Configure SignalR in the Startup class

In the Startup class, we need to add SignalR to the application’s services and middleware.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace YourProjectName
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

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

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<ChatHub>("/chatHub");
            });
        }
    }
}

This code adds SignalR to the application’s services by calling “AddSignalR()” in the “ConfigureServices” method. It then configures the middleware by calling “MapHub()” in the “Configure” method, passing in the URL (“/chatHub”) and the name of the hub class (“ChatHub”).

Step 5: Create the chat UI

Now that we have our SignalR hub set up, we need to create a UI to allow users to send and receive messages.

Create a new folder called “wwwroot” in your project and add a new file called “index.html”. This file will contain the HTML and JavaScript for our chat UI.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>SignalR Chat</title>
</head>
<body>
    <div>
        <input type="text" id="txtUser" placeholder="Your name" />
        <input type="text" id="txtMessage" placeholder="Type a message" />
        <button id="btnSend">Send</button>
    </div>
    <ul id="messages"></ul>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="/chatHub"></script>
    <script>
        var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
         connection.on("ReceiveMessage", function (user, message) {
        var encodedUser = $('<div />').text(user).html();
        var encodedMessage = $('<div />').text(message).html();
        $('#messages').append('<li><strong>' + encodedUser + '</strong>: ' + encodedMessage + '</li>');
    });

    connection.start().then(function () {
        $('#btnSend').click(function () {
            var user = $('#txtUser').val();
            var message = $('#txtMessage').val();
            connection.invoke("SendMessage", user, message);
            $('#txtMessage').val('').focus();
        });
    });
</script>
</body>
</html>

This code defines a simple HTML form with three elements: an input field for the user’s name, an input field for the message, and a button to send the message. It also includes a JavaScript file that sets up a connection to the SignalR hub and handles the sending and receiving of messages.

Step 6: Test the chat application

Run the project and open the chat UI in your web browser. Enter a name and a message and click the “Send” button. You should see the message appear in the chat window in real-time.

Conclusion: In this blog, we learned how to use SignalR in .NET Core to implement real-time communication in a simple chat application. SignalR is a powerful framework that can be used for many types of real-time applications, such as games, chat applications, and live data visualization. I hope this tutorial has been helpful in getting you started with SignalR.

Похожее
Oct 24, 2023
Author: Itexamtools.com
Want to switch to that high paying job? Or are you already been preparing hard to give interview the next weekend?Do you know how many people get rejected in interviews by preparing only concepts but not focusing on actually which...
May 13, 2023
Author: Juan Alberto España Garcia
Introduction to Async and Await in C#Asynchronous programming has come a long way in C#. Prior to the introduction of async and await, developers had to rely on callbacks, events and other techniques like the BeginXXX/EndXXX pattern or BackgroundWorker.These methods...
Mar 22
Author: Dayanand Thombare
IntroductionDelegates are a fundamental concept in C# that allow you to treat methods as objects. They provide a way to define a type that represents a reference to a method, enabling you to encapsulate and pass around methods as parameters,...
Dec 20, 2023
Author: Fiodar Sazanavets
You can run a single monolithic instance of a server application only if the number of clients accessing your application doesn’t exceed a couple of thousand. But what if you expect hundreds of thousands, or even millions, of clients to...
Написать сообщение
Почта
Имя
*Сообщение


© 1999–2024 WebDynamics
1980–... Sergey Drozdov
Area of interests: .NET Framework | .NET Core | C# | ASP.NET | Windows Forms | WPF | HTML5 | CSS3 | jQuery | AJAX | Angular | React | MS SQL Server | Transact-SQL | ADO.NET | Entity Framework | IIS | OOP | OOA | OOD | WCF | WPF | MSMQ | MVC | MVP | MVVM | Design Patterns | Enterprise Architecture | Scrum | Kanban