Introduction:

SignalR is used for adding real time functionalities in web applications.

It’s the functionality where a code circulates content to all the connected clients as soon as the content is posted rather than the conventional method where the server waits for a client to make a fresh request.

Chat application is the most common example of SignalR. In real time, there is much more that can be achieved using SignalR like updating dashboards, real time forms etc.

Description:

In this tutorial, we will have a look at a simple chat like application where data passed from one client will be posted to all the other connected clients without a new request from the connected clients.

For this tutorial, I will be using Visual studio 2019. In visual studio we create a C# ASP.NET Web Application that targets .NET framework then click next.

Give you project a name and set a location for the project. Furthermore, select the framework. In my case the framework used is .NET Framework 4.7.2

Select MVC project on the next screen. Once the project is created, we open the project manager console as below.

And write the following command to install SignalR package.

install-package Microsoft.AspNet.SignalR

After installation is done, you can view installed scripts file in the Script folder of your application

The next step is to create a class file in the project like Startup.cs  and add the following code to it.

using Owin;
using Microsoft.Owin;
[assembly: OwinStartup(typeof(SignalRDemo.Startup))]
namespace SignalRDemo
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

Then create a folder named Hubs in your application. And add a class to it. Give the class a name like ChatHub.cs

Add the following code to it:

using Microsoft.AspNet.SignalR;
namespace SignalRDemo.Hubs
{
    public class ChatHub : Hub
    {
        public void ChatMessage(string name, string message)
        {
            Clients.All.addNewMessageToPage(name, message);
        }
    }
}

Then we add the chat method to the controller and add a view for the same

public ActionResult Chat()
{
     return View();
}

Here is the code for the view page Chat.cshtml

    ViewBag.Title = "Chat";
}

<h2>Chat</h2>
<div class="container">
    <input type="text" id="txtMessage" />
    <input type="button" id="sendmessage" value="Send" />
    <input type="hidden" id="chatUsername" />
    <ul id="chatMessages">
    </ul>
</div>
@section scripts {
    <script src="~/Scripts/jquery.signalR-2.4.3.min.js"></script>
    <script src="~/signalr/hubs"></script>
    
    <script>
        $(function () {
            var chat = $.connection.chatHub;
            chat.client.addNewMessageToPage = function (username, txtMessage) {
                $('#chatMessages').append('<li><strong>' + htmlEncode(username)
                    + '</strong>: ' + htmlEncode(txtMessage) + '</li>');
            };
            
            $('#chatUsername').val(prompt('What is your name?', ''));
            $('#txtMessage').focus();
            
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    chat.server.chatMessage($('#chatUsername').val(), $('#txtMessage').val());
                    $('#txtMessage').val('').focus();
                });
            });
        });

        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}

In the view page make sure you have included the proper script which is installed in your application.

We can now run the application.

Once the browser opens, enter a user name and copy the URL of the application and paste it in other browsers. In each browser enter a distinctive name.

Now add a message in the text box and click on Send button. Do the same in multiple browsers and you will see that the message appears in all browsers real time.

You can observe different browser and see how SignalR works to provide real time chat functionality.

Vibha Munyal

Share
Published by
Vibha Munyal

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago