Introduction
This article gives you a basic idea about the new developer's API called "SignalR".
Background
In earlier ASP.NET applications, user refreshes a web page to see new data or a page uses "long polling" to retrieve new data, i.e., when new data arrives to server it will not be directly transmitted to all clients or specific clients, for that the user has to refresh the page, and the page will be updated.
For example, you can go to cricinfo.com, there you can see a page is refreshed for 1 or 2 seconds and many times you see the score is not updated. In such situations there is the need of the new Microsoft API called "SignalR".
What is SignalR
SignalR is a new developer's API provided for ASP.NET web applications, used to add "real time" web functionality to ASP.NET applications. "Real Time" web functionality is the ability to have server code to push contents to connected clients.
SignalR supports "server push" or "broadcasting" functionality. It handles connection management automatically. In classic HTTP connections for client-server communication connection is re-established for each request, but SignalR provides persistent connection between the client and the server. In SignalR the server code calls out to a client code in the browser using Remote Procedure Calls (RPC), rather than request-response model today. SignalR is an open-source API, and is accessible through GitHub.
Where to use:
- Chat room applications
- Real-time monitoring applications
- Job progress updates
- Real time forms
You can see the use of SignalR for a chat room application in the following image:
In the above example as soon as user2 sends some message, it will be received by all other users.
API Details
SignalR provides two models for communication:
- Persistent Connections
The Persistent Connection API gives developer direct access to the low level communication protocol that SignalR exposes. This API uses the format of the actual message sent that needs to be specified and if the developer prefers to work with messaging and dispatching model rather than a remote invocation.
- Hubs:
It's a High Level API written over PersistentConnection. This API allows the client and server to call methods on each other directly. Hubs also allow you to pass strongly typed parameters to methods, enabling model binding.
Code
Steps:
- Open Visual Studio 2010.
- Create a new project, select ASP.NET Empty Web Application and name it 'ChatRoomApplication'.
- Go to Tools and open Package Manager Console.
- If you don't have a Nuget package manager console then download it. For that go to Tools-->Extension Manager, and in the Search textbox, enter 'NuGet Package Manager', and download it.
- Open Package Manager console (Tools --> Library Package Manager --> Package Manager Console).
- Give command 'Install-Package Microsoft.AspNet.SignalR'.
- It will add references of SignalR DLLs to your application.
- In Solution Explorer right click on ChatRoomApplication and add class "ChatHub". A ChatHub.cs file will be added.
- Derive the
ChatHub
class from 'Hub
'. It should look like:
public class ChatHub : Hub
{
}
Write method Send
in the ChatHub
class as:
public class ChatHub : Hub
{
public void Send(string name, string message)
{
Clients.All.sendMessage(name,message);
}
}
- Now add the Global.asax file to your application. And in the
application_start
event map your hub by RouteTable.Routes.MapHubs()
. It should look like:
protected void Application_Start(object sender,EventArgs e)
{
RouteTable.Routes.MapHubs();
}
- Now add an ASPX page and name it default.aspx
- Copy the following code in the
<head></head>
section:
<script src="http://code.jquery.com/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-1.0.1.min.js" type="text/javascript"></script>
<script src="signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var chat = $.connection.chatHub;
$('#displayname').val(prompt('Enter your name:', ''));
chat.client.sendMessage = function (name, message) {
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
$('#messages').append('<li>' + encodedName +
': ' + encodedMsg + '</li>');
};
$.connection.hub.start().done(function () {
$("#send").click(function () {
chat.server.send($('#displayname').val(), $('#msg').val());
});
});
});
</script>
- Copy the following code into the
<body>
part:
<div>
<input type="text" id="msg" />
<input type="button" id="send" value="Send" />
<input type="hidden" id="displayname" />
<ul id="messages">
</ul>
</div>
- That's it, now run your application, open multiple instances of the browser and copy the same URL there...and type message in the text box, click on the Send button, and you can see the message will be displayed on all browsers.
- For more information, look at the submitted code.