SignalR Minimal Server

Here’s the minimal steps required to create a SignalR server.

  • Create a new ASP.NET Empty Web Applications
  • Use NuGet to add Microsoft ASP.NET SignalR to the project
  • Right mouse click on the project select Add | Global Application Class
  • Edit the Global.asax.cs file to look like the following
    public class Global : System.Web.HttpApplication
    {
       protected void Application_Start(object sender, EventArgs e)
       {
          RouteTable.Routes.MapHubs();
       }
    }
    
  • A a new class file named MyHub and edited it to look like this
    public class MyHub : Hub
    {
       public void Send(string message)
       {
          Clients.All.sendMessage(message);
       }
    }
    
  • Finally we need an index.html pages so right mouse click on the project and select Add | HTMLPage – name it index and press ok. Then edit the file as follows
    <!DOCTYPE html>
    <html>
    <head>
        <title>Minimal SignalR</title>
    
        <script src="../Scripts/jquery-1.6.4.js"></script>
        <script src="../Scripts/jquery.signalR-1.1.2.js"></script>
        <script src="../signalr/hubs"></script>
    
        <script>
            $(function () {
               var monitor = $.connection.myHub;
               monitor.client.sendMessage = function (message) {
                  $('#discussion').append('<li><strong>' + message + '</strong></li>');
              }
              $.connection.hub.start().done(function () {
                  monitor.server.send("Starting...");
              });
            });
        </script>
    </head>
    <body>
        <h2>Minimal SignalR</h2>
    
        <div class="container">
           <ul id="discussion"></ul>
       </div>
    </body>
    
    </html>
    

The above has all the parts required to create a SignalR capable server and script in the HTML file but it doesn’t do anything, that’s for the user to implement, but just as an example to give something to see, let’s edit Global.asax.cs again and change the code to the following

private Timer timer = new Timer(o =>
{
   var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
   context.Clients.All.sendMessage(DateTime.Now.ToLongTimeString() + " beep");
});

protected void Application_Start(object sender, EventArgs e)
{
   RouteTable.Routes.MapHubs();

   TimeSpan ts = TimeSpan.FromSeconds(5);
   timer.Change(ts, ts);
}

The code above will simply send a message every 5 seconds to any listening clients.

Note: You’ll notice how the JavaScript has the MyHub methods etc. in camel case, the proxy automatically does this for us. Also notice the JavaScript call, monitor.server.send uses the Hub method to push a message out when the script starts whereas we subscribe our function to a “known” name, one used in the MyHub (Clients.All.sendMessage). As this is dynamic there’s no compile time check on this, so make sure you get the name and case correct.