Getting started with SignalR

SignalR is a library from Microsoft which can be used for enabling real-time functionality in your web applications. SignalR uses web sockets feature in HTML5 to maintain a persistent connection between the server and the client. Because of the stateless nature of the web, it was very hard to maintain a persistent connection in the pre HTML5 era and we used techniques such as long polling, meta refresh tag or some timer logic coupled with AJAX calls to achieve it. Please visit their site or in GitHub to read more on the features and documentation, also the entire code is available there.

SignalR API contains two methods for communication between client and server

1. Persistent Connections - Represent a single endpoint for sending single-recipient, grouped or broadcast messages. It’s similar to communication based API’s such as WCF.

2. Hubs - Built upon the Connection API that allows the client and server to call methods on each other directly.Similar to other remote invocation API’s such as .NET Remoting

Architecture

 

architecture-diagram

Picture Courtesy : SignalR Documentation

So let’s how we can send messages from server to client using SignalR

First of all you will need to install SignalR and the easiest way to do that is from Nuget using Package manager available in Visual Studio. So create a project first and then install it as shown in the image below, I have used the Package Manager console for installing SignalR and the MVC template for the project

new-project  project-structure

install-package

Now let’s create a Hub class for pushing contents to the clients. The class is derived from the Microsoft.Aspnet.SignalR.Hub class. Here I have used a dynamic property BroadcastMessage to return the string to all the connected clients.

    public class NotificationHub : Hub
    {

        internal static void Trigger()
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
            context.Clients.All.BroadcastMessage("Hello World at " + DateTime.Now.ToString());
            

        }
    }

So let’s add a timer is the Application_Start event in Global.asax file to call the Trigger method in the hub to broadcast the message to various clients periodically

 private static System.Timers.Timer updateTimer;
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            updateTimer = new System.Timers.Timer(10000);
            updateTimer.Elapsed += updateTimer_Elapsed;
            updateTimer.Interval = 60000;
            updateTimer.Enabled = true;
        }

        void updateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Random rnd = new Random();
            updateTimer.Interval = rnd.Next(100, 10000);
            NotificationHub.Trigger();
        }

Now let’s create a view to display the notifications. SignalR is built on top of jQuery, so you should reference jQuery file before adding the reference for SignalR. When you install SignalR from Package Manager console, the js files used by SignalR library will get added to the scripts folder.

    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script src="~/Scripts/jquery.signalR-2.2.0.js"></script>
    <script src="~/signalr/hubs"></script>

So we will now create a proxy for the hub in the client side using the following statement in the document.ready function.

var notification = $.connection.notificationHub;

Here SignalR is following convention over configuration, in server side we will declare the method in camel case and in js the variable will have lower case for the first letter. Now let’s create a callback function in the client side which will be used by the server side code to push content to the client

           notification.client.broadcastMessage = function (message) {
                $("#notifications").prepend('<li><strong>' + message +'</strong></li>')
            };

Finally we will open the connection using the following statement.

$.connection.hub.start();

Here’s the code in full for the view

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title></title>
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script src="~/Scripts/jquery.signalR-2.2.0.js"></script>
    <script src="~/signalr/hubs"></script>
</head>
<body>
    <div id="notifications">
    
    </div>
    <script>
        $(function () {
            var notification = $.connection.notificationHub;
            notification.client.broadcastMessage = function (message) {
                $("#notifications").prepend('<li><strong>' + message +'</strong></li>')
            };

            $.connection.hub.start();
        });
    </script>
</body>
</html>

Before you start the build, you need to add app.MapSignalR() statement in the startup.cs file to enable SignalR in your application.

[assembly: OwinStartupAttribute(typeof(SignalRIntro.Startup))]
namespace SignalRIntro
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            app.MapSignalR();
        }
    }
}

Hit F5 to run the code and open the url in two different browsers and you will that the contents get updated automatically.

output


No Comments

Add a Comment