signalr Getting started with signalr Getting up and running


Example

IIS / .NET version Requirements: See here

SignalR 2+

  1. Install the NuGet package Microsoft.AspNet.SignalR (this is the whole SignalR solution) and it will ask you to install any dependencies for other packages. Accept the terms and install them as well.

  2. Now that we've got the .dlls and client scripts needed to generate our own SignalR Hub, let's create one. Click on your Web project, add a folder named Hubs or SignalR, and in it add a class NameOfYourChoosingHub. I will name mine MessagingHub.cs.

  3. We need to derive from the base class Hub that is in our SignalR dll that we downloaded via NuGet. The code would look like :

    [HubName("messagingHub")]
    public class MessagingHub : Hub
    {
        //empty hub class
    }
    

    And in our Startup.cs class we can let the IAppBuilder know that we are going to use SignalR.

    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
            ConfigureAuth(app);
        }
    }
    
  4. In order to reference our hub code on the Client, we will need to import/reference 2 scripts (Aside from the obvious jQuery reference). The main jQuery.signalR-version.js file and the generated hubs.js file that SignalR generates for our hub specifically. These resources may look like this:

    // script tag src="/YourAppPath/scripts/jquery-1.6.4.js"
    // script tag src="/YourAppPath/scripts/jquery.signalR-2.2.0.js"
    // script tag src="/YourAppPath/signalr/hubs"
    
  5. Since SignalR's JavaScript is built on top of jQuery (requires >= v1.6.4), the code for connecting and disconnecting to the hub should look fairly trivial. Here it is in all its' glory (wrapped in an IIFE) :

    $(function() {
        //notice the camel casing of our hub name corresponding to the [HubName()] attribute on the server
        var connection = $.connection.messagingHub;
    
        $.connection.hub.start().done(function () {
            alert("Connection Successful!");
        }).fail(function (reason) {
            console.log("SignalR connection failed: " + reason);
        });
    });
    
  6. As of right now, we should be able to run the app and establish a connection to the SignalR hub.