"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Tutorial: SignalR Self-Host

by Patrick Fletcher

Download Completed Project

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

Software versions used in the tutorial

Using Visual Studio 2012 with this tutorial

To use Visual Studio 2012 with this tutorial, do the following:

  • Update your Package Manager to the latest version.
  • Install the Web Platform Installer.
  • In the Web Platform Installer, search for and install ASP.NET and Web Tools 2013.1 for Visual Studio 2012. This will install Visual Studio templates for SignalR classes such as Hub.
  • Some templates (such as OWIN Startup Class) will not be available; for these, use a Class file instead.

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, 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:

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. For sample code for hosting a SignalR server in a Windows Service, see Self-Hosting SignalR in a Windows Service.

  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:

    [!code-powershellMain]

       1:  Install-Package Microsoft.AspNet.SignalR.SelfHost

    This command adds the SignalR 2 Self-Host libraries to the project.
  4. In the package manager console, enter the following command:

    [!code-powershellMain]

       1:  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.

    [!code-csharpMain]

       1:  using System;
       2:  using Microsoft.AspNet.SignalR;
       3:  using Microsoft.Owin.Hosting;
       4:  using Owin;
       5:  using Microsoft.Owin.Cors;
       6:   
       7:  namespace SignalRSelfHost
       8:  {
       9:      class Program
      10:      {
      11:          static void Main(string[] args)
      12:          {
      13:              // This will *ONLY* bind to localhost, if you want to bind to all addresses
      14:              // use http://*:8080 to bind to all addresses. 
      15:              // See http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx 
      16:              // for more information.
      17:              string url = "http://localhost:8080";
      18:              using (WebApp.Start(url))
      19:              {
      20:                  Console.WriteLine("Server running on {0}", url);
      21:                  Console.ReadLine();
      22:              }
      23:          }
      24:      }
      25:      class Startup
      26:      {
      27:          public void Configuration(IAppBuilder app)
      28:          {
      29:              app.UseCors(CorsOptions.AllowAll);
      30:              app.MapSignalR();
      31:          }
      32:      }
      33:      public class MyHub : Hub
      34:      {
      35:          public void Send(string name, string message)
      36:          {
      37:              Clients.All.addMessage(name, message);
      38:          }
      39:      }
      40:  }

    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:

    [!code-powershellMain]

       1:  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.

    [!code-htmlMain]

       1:  <!DOCTYPE html>
       2:  <html>
       3:  <head>
       4:      <title>SignalR Simple Chat</title>
       5:      <style type="text/css">
       6:          .container {
       7:              background-color: #99CCFF;
       8:              border: thick solid #808080;
       9:              padding: 20px;
      10:              margin: 20px;
      11:          }
      12:      </style>
      13:  </head>
      14:  <body>
      15:      <div class="container">
      16:          <input type="text" id="message" />
      17:          <input type="button" id="sendmessage" value="Send" />
      18:          <input type="hidden" id="displayname" />
      19:          <ul id="discussion"></ul>
      20:      </div>
      21:      <!--Script references. -->
      22:      <!--Reference the jQuery library. -->
      23:      <script src="Scripts/jquery-1.6.4.min.js"></script>
      24:      <!--Reference the SignalR library. -->
      25:      <script src="Scripts/jquery.signalR-2.1.0.min.js"></script>
      26:      <!--Reference the autogenerated SignalR hub script. -->
      27:      <script src="http://localhost:8080/signalr/hubs"></script>
      28:      <!--Add script to update the page and send messages.-->
      29:      <script type="text/javascript">
      30:          $(function () {
      31:          //Set the hubs URL for the connection
      32:              $.connection.hub.url = "http://localhost:8080/signalr";
      33:              
      34:              // Declare a proxy to reference the hub.
      35:              var chat = $.connection.myHub;
      36:              
      37:              // Create a function that the hub can call to broadcast messages.
      38:              chat.client.addMessage = function (name, message) {
      39:                  // Html encode display name and message.
      40:                  var encodedName = $('<div />').text(name).html();
      41:                  var encodedMsg = $('<div />').text(message).html();
      42:                  // Add the message to the page.
      43:                  $('#discussion').append('<li><strong>' + encodedName
      44:                      + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
      45:              };
      46:              // Get the user name and store it to prepend to messages.
      47:              $('#displayname').val(prompt('Enter your name:', ''));
      48:              // Set initial focus to message input box.
      49:              $('#message').focus();
      50:              // Start the connection.
      51:              $.connection.hub.start().done(function () {
      52:                  $('#sendmessage').click(function () {
      53:                      // Call the Send method on the hub.
      54:                      chat.server.send($('#displayname').val(), $('#message').val());
      55:                      // Clear text box and reset focus for next comment.
      56:                      $('#message').val('').focus();
      57:                  });
      58:              });
      59:          });
      60:      </script>
      61:  </body>
      62:  </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.

    [!code-javascriptMain]
       1:  //Set the hubs URL for the connection
       2:  $.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.



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/signalr/overview/deployment/tutorial-signalr-self-host.htm
< THANKS ME>