Learn to use SignalR in a Web App
SignalR is a library for ASP.NET that give us the possibility to add real-time functionality to our web applications.
The great advantage of use SignalR is that will use WebSockets under the covers when it’s available, and gracefully fallback to other techniques like Server Sent Events → Forever Frames → Long Polling this techniques depends on the client Browser.
How to include SignalR in our project
Our starting point would be an ASP.NET project that has been already created and the steps to follow are:
- We need to install the SignalR nugget package:
- PM> Install-Package Microsoft.AspNet.SignalR
PM> Install-Package Microsoft.AspNet.SignalR.JS
- Wire up SignalR using OWIN: Our Startup.cs must look like
- [assembly: OwinStartup(typeof(Startup))]
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
appBuilder.MapSignalR();
}
}
- Include the jQuery Scripts in html: “The order is important!”
- <!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width” />
<title></title>
</head>
<body>
<script src=”~/Scripts/jquery-1.10.2.js”></script>
<script src=”~/Scripts/jquery.signalR-2.0.2.js”></script>
</body>
</html>
- Create a Hub: We need to create a class that extends from Hub
- public class HelloHub : Hub
{
public void SayHello()
{
Clients.All.hello(“Hello World!”);
}
}
- Connect the client to the Hub using JavaScript:
- <!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width” />
<title></title>
</head>
<body>
<script src=”~/Scripts/jquery-1.10.2.js”></script>
<script src=”~/Scripts/jquery.signalR-2.0.2.js”></script> - <script type=”text/javascript”>
$(function () {
// create a signalr connection
var con = $.hubConnection();
// create a hub proxy
var hub = con.createHubProxy(‘helloHub’); - // an event handler for a hub-generated event
hub.on(‘hello’, function (greeting) {
$(‘#counter’).text(greeting);
}); - // start the connection
con.start.done(function () {
// we’re connected now
hub.invoke(‘sayHello’);
});
});
</script>
</body>
</html>
For more information about SignalR go to the oficial page at http://signalr.net/