The HTTP protocol of the internet works on a stateless model and hence every time the client makes a request to the server to get data and once the server sends the response out to the client, the connection is closed, and there is nothing that the server can send over the connection to the client. Microsoft provides ASP.NET SignalR to do the real-time web functionality where the server can push the updates to the client when it has any. The client must first make a request to the servers to get the updated data.
The real-time communication uses techniques such as Polling, Long Polling and so on.
Real-time communication is most used in chat applications, gaming applications and many other monitoring applications like Stock Exchange applications for showing updates in the stock market every second.
HTML5 Web Sockets is also one of the techniques to do Real-time Communication and SignalR also uses Web Sockets under the hood to do this wherever Web Sockets can work, else it falls back to Long Polling and Polling techniques. One can use Web Sockets but the benefit we get by using SignalR is that while using Web Sockets you need to write a lot of code to do all the real-time functionalities whereas SignalR provides you with the API(s) for doing all of it. Also you don't need to worry while implementing SignalR if the client and server supports Web Socket Connections, if the connections are supported then SignalR will use Web Sockets under the hood and if not it will fall back to other techniques for achieving Real-time Communication.
SignalR provides APIs for managing the connections, connections from various clients, and also provides the ability of the server to push the messages to the client by calling the methods defined on the client-side in JavaScript using Remote Procedure Calls. Similarly, the client can also call methods on the server-side on the same established connection. The API that helps in doing so is known as "Hubs".
So you can use various Hubs in your application for the various real-time functionalities. So all the communication that will be done for a specific functionality will be defined in the Hub, and the code is responsible for handling any messages coming from the client and sent to the client.
Microsoft provides SignalR as a NuGet package that comes with all the server components required at the server-side and the JavaScript files required at the client-side for real-time communication. I will show you how to create a sample application using SignalR, I was just eager to write it down when I got a query in the comment on the article of HTML5 WebSockets, saying "Which one is better??" It's better to be late than never... :)
I hope this article will help to determine which one is better for them, if you are using Microsoft Technologies then I will recommend using with SignalR rather than Web Sockets, since it will save a lot of Development effort and will use Web Sockets under the hood, wherever it is supported.
For downloading the SignalR package, just open up the Package Manager Console and type in the following command:
PM> Install-Package Microsoft.AspNet.SignalR
For creating a sample application, I have created a sample Web site. Now download the SignalR package using the command above in the Package Manager Console.
As soon as you have downloaded the package you will see that some DLL(s) required for SignalR and some of the JavaScript files required at the client side are automatically added into your sample project or website, whatever you are creating.
I will create a simple chat application that I also demonstrated while writing article about HTML5 Web Sockets, and here you will see the difference. If you compare both then you will see that SignalR has removed much of the coding effort by providing API(s) required for Real-time Communication.
Add a class in which we will write code for the communication between the client and the server. This class will be inherited from the Hubs class provided in SignalR API(s). In this class I created a method "SendMessage". This is the method to which the client will make a request to whenever it wants to broadcast a message for other users. And in this method we have written the code that broadcasts this message to all the clients by calling the "MessageRecieved" method on the client side. In the "MessageRecieved" method we will receive the message and we can use JavaScript to display this message by putting it into the HTML DOM.
using Microsoft.AspNet.SignalR;
/// <summary>
/// Summary description for ChatHub
/// </summary>
public class ChatHub : Hub
{
public void SendMessage(string message)
{
Clients.All.MessageRecieved(message);
}
}
Another class that is there is required for doing the configuration, the configuration of the Hub Configuration is like, if we need CORS in between or we want to enable a Cross Domain Request by enabling JSONP requests. So if you are using multiple Hubs then the entire configuration can go into this class. This class is the OWIN start-up class and we will define it as the OWIN start-up class by making the following entry into the "Web.Config" file.
<appSettings>
<add key="owin:appStartup" value="StartupClass"/>
</appSettings>
Startup Class
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(StartupClass))]
/// <summary>
/// Summary description for StartupClass
/// </summary>
public class StartupClass
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
And with this we are ready to go. I have created a sample page for demonstration.
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="Scripts/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.signalR-2.0.0.min.js"></script>
<script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>
</head>
<body>
<form id="form1" runat="server">
Message:
<input type="text" id="txtMessage" /> <input type="button" id="btnBroadcastMessage" value="Broadcast" /><br />
<div id="divMessages">
</div>
<script type="text/javascript">
$(function () {
var chatHub = $.connection.chatHub;
$.connection.hub.start().done(function () {
$("#btnBroadcastMessage").click(function () {
chatHub.server.sendMessage($('#txtMessage').val());
});
}).fail(function (data) { alert(data) });
chatHub.client.MessageRecieved = function (message) {
$('#divMessages').append(message + '<br/>');
};
});
</script>
</form>
</body>
</html>
Running Sample
I think this has made it clear that it is so much easier to use SignalR, whereas one has to put a lot of effort into creating a similar application with Web Sockets. I am also attaching the sample code, that you can execute at your end and see the results. Yes much more can be done using configurations, writing down a small piece of code can help you in doing a lot; a Security API is also there for security purposes.