Language

Tutorial: SignalR Self-Host

By Patrick Fletcher|

This tutorial shows how to create a self-hosted SignalR 2.0 server, and how to connect to it with a JavaScript client.

Software versions used in the tutorial


Questions and comments

Please leave feedback on how you liked this tutorial and what we could improve in the comments at the bottom of the page. If you have questions that are not directly related to the tutorial, you can post them to the ASP.NET SignalR forum or StackOverflow.com.

Overview

A SignalR server is usually hosted in an ASP.NET application in IIS, but it can also be self-hosted (such as in a console application or Windows service) using the self-host library. This library, like all of SignalR 2.0, is built on OWIN (Open Web Interface for .NET). OWIN defines an abstraction between .NET web servers and web applications. OWIN decouples the web application from the server, which makes OWIN ideal for self-hosting a web application in your own process, outside of IIS.

Reasons for not hosting in IIS include:

  • Environments where IIS is not available or desirable, such as an existing server farm without IIS.
  • The performance overhead of IIS needs to be avoided.
  • SignalR functionality is to be added to an exising application that runs in a Windows Service, Azure worker role, or other process.

If a solution is being developed as self-host for performance reasons, it's recommended to also test the application hosted in IIS to determine the performance benefit.

This tutorial contains the following sections:

Creating the server

In this tutorial, you'll create a server that's hosted in a console application, but the server can be hosted in any sort of process, such as a Windows service or Azure worker role.

  1. Open Visual Studio 2013 with administrator privileges. Select File, New Project. Select Windows under the Visual C# node in the Templates pane, and select the Console Application template. Name the new project "SignalRSelfHost" and click OK.

  2. Open the library package manager console by selecting Tools, Library Package Manager, Package Manager Console.

  3. In the package manager console, enter the following command:

    Install-Package Microsoft.AspNet.SignalR.SelfHost

    This command adds the SignalR 2.0 Self-Host libraries to the project.

  4. In the package manager console, enter the following command:

    Install-Package Microsoft.Owin.Cors

    This command adds the Microsoft.Owin.Cors library to the project. This library will be used for cross-domain support, which is required for applications that host SignalR and a web page client in different domains. Since you'll be hosting the SignalR server and the web client on different ports, this means that cross-domain must be enabled for communication between these components.

  5. Replace the contents of Program.cs with the following code.

            
    using System;
    using Microsoft.AspNet.SignalR;
    using Microsoft.Owin.Hosting;
    using Owin;
    using Microsoft.Owin.Cors;
    
    namespace SignalRSelfHost
    {
        class Program
        {
            static void Main(string[] args)
            {
                // This will *ONLY* bind to localhost, if you want to bind to all addresses
                // use http://*:8080 to bind to all addresses. 
                // See http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx 
                // for more information.
                string url = "http://localhost:8080";
                using (WebApp.Start(url))
                {
                    Console.WriteLine("Server running on {0}", url);
                    Console.ReadLine();
                }
            }
        }
        class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                app.UseCors(CorsOptions.AllowAll);
                app.MapSignalR();
            }
        }
        public class MyHub : Hub
        {
            public void Send(string name, string message)
            {
                Clients.All.addMessage(name, message);
            }
        }
    }    
    

    The above code includes three classes:

    • Program, including the Main method defining the primary path of execution. In this method, a web application of type Startup is started at the specified URL (http://localhost:8080). If security is required on the endpoint, SSL can be implemented. See How to: Configure a Port with an SSL Certificate for more information.

    • Startup, the class containing the configuration for the SignalR server (the only configuration this tutorial uses is the call to UseCors), and the call to MapSignalR, which creates routes for any Hub objects in the project.

    • MyHub, the SignalR Hub class that the application will provide to clients. This class has a single method, Send, that clients will call to broadcast a message to all other connected clients.

  6. Compile and run the application. The address that the server is running should show in a console window.

  7. If execution fails with the exception System.Reflection.TargetInvocationException was unhandled, you will need to restart Visual Studio with administrator privileges.
  8. Stop the application before proceeding to the next section.

Accessing the server with a JavaScript client

In this section, you'll use the same JavaScript client from the Getting Started tutorial. We'll only make one modification to the client, which is to explicitly define the hub URL. With a self-hosted application, the server may not necessarily be at the same address as the connection URL (due to reverse proxies and load balancers), so the URL needs to be defined explicitly.

  1. In Solution Explorer, right-click on the solution and select Add, New Project. Select the Web node, and select the ASP.NET Web Application template. Name the project "JavascriptClient" and click OK.

  2. Select the Empty template, and leave the remaining options unselected. Select Create Project.

  3. In the package manager console, select the "JavascriptClient" project in the Default project drop-down, and execute the following command:

    Install-Package Microsoft.AspNet.SignalR.JS

    This command installs the SignalR and JQuery libraries that you'll need in the client.

  4. Right-click on your project and select Add, New Item. Select the Web node, and select HTML Page. Name the page Default.html.

  5. Replace the contents of the new HTML page with the following code. Verify that the script references here match the scripts in the Scripts folder of the project.

            
    <!DOCTYPE html>
    <html>
    <head>
        <title>SignalR Simple Chat</title>
        <style type="text/css">
            .container {
                background-color: #99CCFF;
                border: thick solid #808080;
                padding: 20px;
                margin: 20px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <input type="text" id="message" />
            <input type="button" id="sendmessage" value="Send" />
            <input type="hidden" id="displayname" />
            <ul id="discussion"></ul>
        </div>
        <!--Script references. -->
        <!--Reference the jQuery library. -->
        <script src="Scripts/jquery-1.6.4.min.js"></script>
        <!--Reference the SignalR library. -->
        <script src="Scripts/jquery.signalR-2.0.3.min.js"></script>
        <!--Reference the autogenerated SignalR hub script. -->
        <script src="http://localhost:8080/signalr/hubs"></script>
        <!--Add script to update the page and send messages.-->
        <script type="text/javascript">
            $(function () {
            //Set the hubs URL for the connection
                $.connection.hub.url = "http://localhost:8080/signalr";
                
                // Declare a proxy to reference the hub.
                var chat = $.connection.myHub;
                
                // Create a function that the hub can call to broadcast messages.
                chat.client.addMessage = function (name, message) {
                    // Html encode display name and message.
                    var encodedName = $('<div />').text(name).html();
                    var encodedMsg = $('<div />').text(message).html();
                    // Add the message to the page.
                    $('#discussion').append('<li><strong>' + encodedName
                        + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
                };
                // Get the user name and store it to prepend to messages.
                $('#displayname').val(prompt('Enter your name:', ''));
                // Set initial focus to message input box.
                $('#message').focus();
                // Start the connection.
                $.connection.hub.start().done(function () {
                    $('#sendmessage').click(function () {
                        // Call the Send method on the hub.
                        chat.server.send($('#displayname').val(), $('#message').val());
                        // Clear text box and reset focus for next comment.
                        $('#message').val('').focus();
                    });
                });
            });
        </script>
    </body>
    </html>
            
        

    The following code (highlighted in the code sample above) is the addition that you've made to the client used in the Getting Stared tutorial (in addition to upgrading the code to SignalR version 2 beta). This line of code explicitly sets the base connection URL for SignalR on the server.

    
    //Set the hubs URL for the connection
    $.connection.hub.url = "http://localhost:8080/signalr";
                 
  6. Right-click on the solution, and select Set Startup Projects.... Select the Multiple startup projects radio button, and set both projects' Action to Start.

  7. Right-click on "Default.html" and select Set As Start Page.

  8. Run the application. The server and page will launch. You may need to reload the web page (or select Continue in the debugger) if the page loads before the server is started.

  9. In the browser, provide a username when prompted. Copy the page's URL into another browser tab or window and provide a different username. You will be able to send messages from one browser pane to the other, as in the Getting Started tutorial.

Author Information

Patrick Fletcher

Patrick Fletcher – Patrick Fletcher is a programmer-writer on the ASP.NET team, currently working on SignalR.