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

Introduction to SignalR

0.00/5 (No votes)
14 May 2013 1  
This article gives you a basic idea about the new developer's API called SignalR.

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:

  1. Chat room applications
  2. Real-time monitoring applications
  3. Job progress updates
  4. 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:

  1. Persistent Connections
  2. 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.

  3. Hubs:
  4. 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:

  1. Open Visual Studio 2010.
  2. Create a new project, select ASP.NET Empty Web Application and name it 'ChatRoomApplication'.
  3. Go to Tools and open Package Manager Console.
  4. 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.
  5. Open Package Manager console (Tools --> Library Package Manager --> Package Manager Console).
  6. Give command 'Install-Package Microsoft.AspNet.SignalR'.
  7. It will add references of SignalR DLLs to your application.
  8. In Solution Explorer right click on ChatRoomApplication and add class "ChatHub". A ChatHub.cs file will be added.
  9. Derive the ChatHub class from 'Hub'. It should look like:
  10. 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);
        }
    }
  11. 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:
  12. protected void Application_Start(object sender,EventArgs e)
    {
        RouteTable.Routes.MapHubs();
    }
  13. Now add an ASPX page and name it default.aspx
  14. Copy the following code in the <head></head> section:
  15. <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 () {
            // Proxy created on the fly          
            var chat = $.connection.chatHub;
    
            // Get the user name and store it to prepend to messages.
            $('#displayname').val(prompt('Enter your name:', ''));
    
            // Declare a function on the chat hub so the server can invoke it          
            chat.client.sendMessage = function (name, message) {
    			var encodedName = $('<div />').text(name).html();
    			var encodedMsg = $('<div />').text(message).html();
    			$('#messages').append('<li>' + encodedName + 
    			    ':  ' + encodedMsg + '</li>');
            };
    
            // Start the connection
            $.connection.hub.start().done(function () {
                $("#send").click(function () {
                    // Call the chat method on the server
                    chat.server.send($('#displayname').val(), $('#msg').val());
                });
            });
        });
    </script>
    
  16. Copy the following code into the <body> part:
  17. <div>
    <input type="text" id="msg" />
    <input type="button" id="send" value="Send" />
    <input type="hidden" id="displayname" />
    <ul id="messages">
    </ul>
    </div>
  18. 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.
  19. For more information, look at the submitted code.

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