SignalR Chat

Even if a pure Web Socket solution isn’t possible yet there are perfectly good alternatives. And the one I really like is SignalR as it allows for the same kind of application today. Check out a live demo of a simple chat application here.

So if SignalR works today does it mean it doesn’t use Web Sockets? Well it might or might not depending on the circumstances. SignalR actually provides an abstraction layer over the actual transport used. And depending on the client and sever capabilities it can use one or 4 different networking techniques

  • WebSockets
  • Server Send Events
  • Forever frame
  • Long polling

It just chooses the best solution that both the browser and server support.

Client side code

The client side JavaScript is quite simple.

$(function () {
    var hub = $.connection.signalRChatHub;
    $.connection.hub.start();
 
    hub.ChatMessage = function (msg) {
        $('<li>').text(msg).prependTo('#messages');
    };
 
    $('#btn').click(function () {
        var txt = $('#txt').val();
        hub.sendMessage(txt);
        $('#txt').val('').focus();
    });
});

Server side code

The server side implementation of SignalR is also quite nice. All I had to do is add the SignalR nuget package and create a class deriving from Hub.

public class SignalRChatHub : Hub
{
    public void SendMessage(string message)
    {
        Clients.ChatMessage("Echo " + message);
    }
}