Click here to Skip to main content
15,884,388 members
Articles / Web Development / ASP.NET

What is SignalR and Why Should I Use It?

Rate me:
Please Sign up or sign in to vote.
4.66/5 (28 votes)
18 Apr 2016CPOL3 min read 44K   35   8
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.

C#
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.

C#
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.

JavaScript
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/jquery.signalR-2.2.0.js"></script>
<script src="~/signalr/hubs"></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.

JavaScript
$(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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Canada Canada
Cindy Potvin is a software developer based in the Montreal area. At her day job, she creates web applications using the ASP.NET MVC framework and mobile applications using the Android SDK.

Comments and Discussions

 
SuggestionA simple app using this method as a sample will be very userful Pin
Member 109742897-Jun-16 18:50
Member 109742897-Jun-16 18:50 
PraiseThank you Pin
Member 1067628120-Apr-16 21:05
Member 1067628120-Apr-16 21:05 
PraiseWell Done! Pin
Member 1075361520-Apr-16 7:29
Member 1075361520-Apr-16 7:29 
QuestionHow use SignalR for remote device control Pin
Gerry Softman2-Apr-15 6:51
professionalGerry Softman2-Apr-15 6:51 
AnswerRe: How use SignalR for remote device control Pin
Cindy Potvin2-Apr-15 16:10
Cindy Potvin2-Apr-15 16:10 
QuestionExcellent Article! Pin
Your Display Name Here24-Mar-15 14:37
Your Display Name Here24-Mar-15 14:37 
General5! Pin
BigWCat24-Mar-15 5:59
professionalBigWCat24-Mar-15 5:59 
GeneralGreat arcticle ! Pin
Jean-Francois Gouin24-Mar-15 3:39
Jean-Francois Gouin24-Mar-15 3:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.