SignalR .NET client

I’ve been using SignalR from a browser but decided I wanted to try the .SignalR .NET Client code as well to see how to implement such an app. I’m not going to cover the server exception to show the Hub

public class MonitorServiceHub : Hub
{
   public void ProjectUpdate(string message)
   {
      Clients.All.projectUpdated(message);
   }
}

It’s very simple as you see. This pushed messages out to anything subscribed to the “projectUpdated” function.

So in JavaScript we have the following for the browser

<script>
var monitor = $.connection.monitorServiceHub;
monitor.client.projectUpdated = function (message) {
   $('#latest').append('<li>' + message + '</li>');
}
$.connection.hub.start().done(function () {
   monitor.server.projectUpdate("Starting Monitor");
});
</script>

So how to we create a SignalR client ?

  • Create a new Console application in Visual Studio 2012
  • Use NuGet to add the Microsoft ASP.NET SignaalR Client
  • Now, simple add the following code
    static void Main(string[] args)
    {
       HubConnection connection = new HubConnection("http://localhost/test/");
       IHubProxy proxy = connection.CreateHubProxy("monitorServiceHub");
       connection.Start().ContinueWith(task =>
       {
          proxy.Invoke("ProjectUpdate", ".NET Client Connected");
    
          proxy.On<string>("projectUpdated", (message) =>
          {
             Console.WriteLine(message);
          });
       });
       Console.Read();
    }
    

Obviously replace the http://localhost/test/ with the location of your server. This line creates the connection (as the name suggests) and then we create the proxy. Notice we use the camel case name as created by the proxy. Next we start the connection and set up a ContinueWith where the communications takes place. I’ve added code to send a message out (just to demonstrate how) using Invoke, so all clients will see when the .NET client connects. Notice this uses the method name on the class not the camel case naming. Finally we in essence subscribe to the projectUpdated messages/function and simply output whatever message we get to the Console.