Sony Arouje

a programmer's log

Archive for October 2nd, 2012

SignalR – Real time pushing of data to connected clients

with 25 comments

Updated post about how to create a chat application using SignalR 2.1

How many times you might have refreshed your browser to see the updated score of a cricket match or refresh to get the updated stock details. Isn’t that cool if the browser can display the updated data without refreshing or doing a page load. Yes it is, then the next question come to mind is how to implement it using .NET technology. There is no straight forward approach, most of them have loads of code.

So how do we achieve it? The answer is SignalR. Scott Hanselman have a nice post about SignalR. In his post he explains a small chat application using 12 lines of code.

I wanted a real time pushing of data to ASP.NET, Javascript client or desktop clients for a project I am working on. The details of that project I will post it later. I am aware of SignalR but never really tried or doesn’t know how to make it work. Yesterday I decided to write a tracer to better understand how SignalR works. This post is all about that tracer I created.

Tracer Functionality

The functionality is very simple. I need two clients a console and a web app. Data entered in any of these clients should reflect in other one. A simple functionality to test SignalR.

Let’s go through the implementation.

I have three projects in my solution 1. SignalR self hosted server 2. A console Client 3. A Web application.

SignalR server

Here I used a self hosting option. That means I can host the server in Console or Windows service. Have a look at the code.

using System;
using System.Threading.Tasks;
using SignalR.Hosting.Self;
using SignalR.Hubs;
namespace Net.SignalR.SelfHost
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "http://localhost:8081/";

            var server = new Server(url);
            server.MapHubs();
            
            server.Start();
            Console.WriteLine("SignalR server started at " + url);

            while (true)
            {
                ConsoleKeyInfo ki = Console.ReadKey(true);
                if (ki.Key == ConsoleKey.X)
                {
                    break;
                }
            }
        }

        public class CollectionHub : Hub
        {
            public void Subscribe(string groupName)
            {
                Groups.Add(Context.ConnectionId, groupName);
                Console.WriteLine("Subscribed to: " + collectionName);
            }

            public Task Unsubscribe(string groupName)
            {
                return Clients[groupName].leave(Context.ConnectionId);
            }

            public void Publish(string message, string groupName)
            {
                Clients[groupName].flush("SignalR Processed: " + message);
            }
        }

    }
}

As you can see from the main I hosted the SignalR server in a specific URL. You can see another Class called CollectionHub inherited from Hub. So what is a hub? Hubs provide a higher level RPC framework, client can call the public functions declared in the hub. In the above Hub I declared Subscriber, Unsubscribe and Publish function. The clients can subscribe to messages by providing a Collection Name, it’s like joining to a chat room. Only the members in that group receives all the messages.

You will notice another function called Publish with a message and a groupName. The clients can call the publish method by passing a message and a group name. SignalR will notify all the clients subscribed to that group with the Message passed. So what’s this ‘flush’ function called in publish, it’s nothing but the function defined in the client. We will see that later.

We are done, run the console application and our SignalR server is ready to receive requests.

SignalR clients

First we will look into a Console client. Let’s see the code first.

using SignalR.Client.Hubs;
namespace Net.SignalR.Console.Client
{
    class Program
    {
        static void Main(string[] args)
        {
            var hubConnection = new HubConnection("http://localhost:8081/");
            var serverHub = hubConnection.CreateProxy("CollectionHub");
            serverHub.On("flush", message => System.Console.WriteLine(message));
            hubConnection.Start().Wait();
            serverHub.Invoke("Subscribe", "Product");
            string line = null;
            while ((line = System.Console.ReadLine()) != null)
            {
                // Send a message to the server
                serverHub.Invoke("Publish", line, "Product").Wait();
            }

            System.Console.Read();
        }
    }
}

Let’s go line by line.

  1. Create a hub connection with the url where SignalR server is listening.
  2. Create a proxy class to call functions in CollectionHub we created in the server.
  3. Register an event and callback, so that Server can call client and notify updates. As you can the Event name is ’Flush’, if you remember the server calls this function in Publish function to update the message to clients.
  4. Start the Hub and wait to finish the connection.
  5. We can call any public method in declared in Hub using the Invoke method by passing the function name and arguments.

Run the console application and type anything and hit enter. You can see some thing like below.

image

The name prefixed ‘SignalR Processed’ is the message back from the SignalR server. So we are done with a console application.

Now how about we have to display the updates in a web application. Let’s see how to do it in web application. In web application I used javascript to connect to the SignalR server.

<html xmlns="http://www.w3.org/1999/xhtml">
    <script src ="Scripts/json2.js" type="text/jscript"></script>
    <script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.signalR-0.5.3.min.js" type="text/javascript"></script>
    <script type="text/javascript">
           $(function () {
               var connection = $.hubConnection('http://localhost:8081/');
               proxy = connection.createProxy('collectionhub')
               connection.start()
                    .done(function () {
                        proxy.invoke('subscribe', 'Product');
                        $('#messages').append('<li>invoked subscribe</li>');
                    })
                    .fail(function () { alert("Could not Connect!"); });


               proxy.on('flush', function (msg) {
                   $('#messages').append('<li>' + msg + '</li>');
               });

               $("#broadcast").click(function () {
                   proxy.invoke('Publish', $("#dataToSend").val(), 'Product');
               });

           });
    </script>
    <body>
        <div>
            <ul id="messages"></ul>
            <input type="text" id="dataToSend" />
            <input id="broadcast" type="button" value="Send"/>
        </div>
    </body>
</html>

 

You can install SignalR Javascript client from Nuget and it will install all the required js files. The code looks very similar to the one in Console application. So not explaining in detail.

 

Now if you run all three application together and any update in one client will reflect in other. As you can see in web client we use Javascript for DOM manipulation, so the page will never refresh but you will see the updated info.

image

I hope this post might help you to get started with SignalR.

Dowload the source code.

Happy coding….

Written by Sony Arouje

October 2, 2012 at 4:48 pm

Posted in .NET

Tagged with , ,

%d bloggers like this: