Using SignalR for real time communication on the web
Monday 09 July 2012
In a previous blog post I mentioned how exited I was about WebSockets and the future with real time duplex communication over the Internet. Unfortunately the current support for WebSockets, both on the client and on the server, is still somewhat limited making this a thing of the future. Does that mean we can do this yet? Not quite.
SignalR to the resque
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
- Server Send Events
- Forever frame
- Long polling
It just chooses the best solution that both the browser and server support.
SignalR is multi browser
I have create a simple chat page using SignalR and as you can see in the screenshot below it supports lots of browsers on different platforms, here I used desktop IE, Chrome and FireFox as wel as my iPad and Windows Phone 7. All of these just work with SignalR. Pretty good as Web Sockets would only work on Chrome and FireFox at the moment.
The client side code
The HTML markup required is really simple
The server parts
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.
Check out a live demo here.