The Real-Time Web With SignalR

Today for RECESS I looked into SignalR.  The SignalR site (which currently is just the github repository) describes it as an “async signaling library for ASP.NET to help build real-time, multi-user interactive web applications.”  What does this mean to you and me?  This library allows you, in just a few lines of code, communicate in real-time amongst browsers that are hitting your site.

Scott Hanselman does a good job of summarizing what SignalR does and how we got here, so I won’t repeat it here.

I followed the super quick sample – a browser based chat application as described Scott’s post.  I ran out of time before I could get the lower level connection working, but the higher level “Hub” based connection works great.

It’s super cool to see it working – I have 3 different browsers (IE, Chrome, Firefox) in the chat together.  When I enter a chat message in one, the other two receive the message instantaneously.

    $("#broadcast").click(function () {
      // send() is the method on the ASP.NET Hub class running on the server
      chat.send($('#msg').val());
    });

The use of dynamic objects in the ASP.NET implementation of the Hub allows me to call any method on the Hub, as long as that function exists in the client side JavaScript.

    public class Chat : Hub
    {
        public void Send( string message )
        {
            // addMessage is a client side javascript function
            Clients.addMessage(message);  
        }
    }

Here’s a couple shots of IE Developer Tools (F12) when running the chat client.

Waiting for a response on the first call to signalr/connect:

CropperCapture81

Got the response from the first connect (a message was broadcast to all the clients), now turn right around and connect to wait for the next “reply” from the server:

CropperCapture82

 


 

Leave a Reply

Your email address will not be published. Required fields are marked *