Click here to Skip to main content
15,880,469 members
Articles / Programming Languages / C# 4.0
Tip/Trick

Introduction to SignalR

Rate me:
Please Sign up or sign in to vote.
4.73/5 (33 votes)
14 May 2013CPOL3 min read 162.1K   7.3K   54   16
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:

Image 1

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. C#
    public class ChatHub : Hub
    {
    }

    Write method Send in the ChatHub class as:

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


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionPronounciation Pin
gardnerp20-Jun-19 5:20
gardnerp20-Jun-19 5:20 
GeneralMy vote of 4 Pin
Member 1144475213-Apr-16 0:41
Member 1144475213-Apr-16 0:41 
GeneralMy vote of 3 Pin
ProCoderSaurabh2-Nov-15 20:59
ProCoderSaurabh2-Nov-15 20:59 
GeneralMy Vote of 5 Pin
Umesh Bhosale6-Jul-15 18:32
Umesh Bhosale6-Jul-15 18:32 
QuestionOwin Startup Class Pin
tehtb22-Mar-15 21:44
tehtb22-Mar-15 21:44 
AnswerRe: Owin Startup Class Pin
Sim294-Jun-17 15:45
professionalSim294-Jun-17 15:45 
QuestionComments Pin
AjayJamwal16-Jul-14 22:23
professionalAjayJamwal16-Jul-14 22:23 
AnswerRe: Comments Pin
Amol Shelar10115-Dec-14 20:27
Amol Shelar10115-Dec-14 20:27 
Questionhow to use signalR in vs2008 Pin
mahesh chikhale26-Mar-14 12:01
mahesh chikhale26-Mar-14 12:01 
AnswerRe: how to use signalR in vs2008 Pin
Amol Shelar10115-Dec-14 20:26
Amol Shelar10115-Dec-14 20:26 
QuestionVersion Conflict Pin
Arunprasath Natarajan24-Mar-14 21:44
Arunprasath Natarajan24-Mar-14 21:44 
GeneralMy vote of 4 Pin
Saeid198412-Feb-14 1:28
Saeid198412-Feb-14 1:28 
QuestionHow to Create a Visual Basic Project to connect with the Website? Pin
Mikloo2-Dec-13 12:15
Mikloo2-Dec-13 12:15 
GeneralMy vote of 3 Pin
Rohit Taralekar9-May-13 22:01
Rohit Taralekar9-May-13 22:01 
QuestionMight want to fix the spelling of SignalR Pin
ednrg9-May-13 9:39
ednrg9-May-13 9:39 
Might want to fix the spelling of SignalR, you spelled it SiganlR. Might be hard to find in a search.
AnswerRe: Might want to fix the spelling of SignalR Pin
Rohit Taralekar9-May-13 18:15
Rohit Taralekar9-May-13 18:15 

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.