Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

What is SignalR and Why Should I Use It?

0.00/5 (No votes)
18 Apr 2016 1  
What is SignalR and why should I use it?

When I first heard about SignalR, I was not sure what was the point of it. The official description says that SignalR is a library that can be used with any ASP.NET application to add real-time communication. But since what they meant by real-time was not totally clear to me, and the only example was a chat room, I pushed it aside for a while.

When I started to work on my side project, I also started thinking about SignalR again. One of the things I want to do was refresh the schedule as soon as a change was made: if a user makes a modification, it should be visible to all other users. The classic way to do something like that would be to call the server at regular intervals to get the status of the schedule, but to have pseudo real-time update, you must call the server pretty often.

With SignalR, the server can call a JavaScript methods on all the clients by itself when updates are required. The library will handle the connection needed to achieve this: by default WebSocket is used, but it will fallback automatically to older connections types if WebSocket is not available in the browser. The JavaScript can also call the server: this can already be done with AJAX, but if two-way communication is needed it may be easier and cleaner to do it all with SignalR.

So, using a real-time library is the way to go if you want to build an application that requires collaboration between users. Common uses cases includes editors, social networks, chats or a schedule like my project.

Getting started with SignalR is pretty simple. Here is an example with my side project: sessions for an event can be modified by any user, and when a session is modified the change is visible for all the user currently logged in the application.

On the Server

First, you must add the Microsoft ASP.NET SignalR package to your ASP.NET application using NuGet, along with the jQuery package if you don’t already have it.

After this, you must create a class that derives from the Hub class. All the methods of the hub can be called from JavaScript. Also, those methods can call JavaScript methods on the client.

namespace EventScheduling
{
public class SessionsHub : Hub
   {
   public void SessionModified(ScheduledSession scheduledSession)
      {
      // Call the JavaScript method sendSessionChanged on all the clients
      Clients.All.sendSessionChanged(scheduledSession);
      }
   }
}

To enable communications between the hub and the JavaScript, you must also enable SignalR in the Configuration method in the Startup class of your application.

namespace EventScheduling
{
public class Startup
   {
   public void Configuration(IAppBuilder app)
      {
      app.MapSignalR();
      }
   }
}

On the Client

On the client, you must include the jquery.signalR-2.2.0.js file containing the JavaScript for the SignalR library and the package ~/signalr/hubs. This package is automatically generated from your Hub classes and contains all the JavaScript required to call the server and receive message from the server.

<script src="/Scripts/jquery-1.10.2.js"></script>

After this, when the page is loaded and ready, you must declare the JavaScript function called by the server-side code. Since the Hub class is called SessionsHub and the SessionModified method of the hub class calls the sendSessionChanged method, this function must be declared in the $.connection.sessionsHub.client.sendSessionChanged variable.

Once this function is created, you must also connect to the hubs using the $.connection.hub.start method. You can also add initialization code in the done() callback which will be called when the connection is started.

$(document).ready(function () {
   // Create a function that the hub can call to broadcast messages.
   $.connection.sessionsHub.client.sendSessionChanged = function (session) {
      // Display the session again using the new data received from the server
      });
   };

   // Start the connection and create a function that the hub will call when loaded
   $.connection.hub.start().done($("#Sessions").on("click", ".Session", function (event) {
      var that = $(this);
      var currentSession = that.data("session");
      currentSession.Title = currentSession.Title + "Clicked";
      // Call the server, which will notify all clients of the change in the title
      $.connection.sessionsHub.server.sessionModified(currentSession);
   }));
});

In the example, when the hubs are done starting, a click handler is added to each session on the page. When the users clicks a session, the word Clicked is added to the title of that session, and all browsers showing the page are notified. Since the SessionModified method was declared in the SessionsHub class of the server, it can be called from JavaScript using the $.connection.sessionsHub.server.sessionModified method.

With only this small bit of code, you now have two-way communications between the client and the server, which you can use to update data in real-time for your users. I will use SignalR in future projects, that’s for sure!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here