WYSIWYG

http://kufli.blogspot.com
http://github.com/karthik20522

Friday, March 16, 2012

SignalR - Web Sockets

SignalR is a cool asynchronous signaling library for ASP.NET to build real-time applications or for any push based notifications. SignalR is similar to Socket.IO or NowJS. Before the workd of web-sockets, there was Comet which was basically a long-held HTTP requests.

SignalR can be downloaded from NuGet [http://www.nuget.org] and downloading the files manually from Git [https://github.com/SignalR/SignalR]

More descriptive information on SignalR can be found at Scott Hanselman’s site [http://www.hanselman.com/blog/AsynchronousScalableWebApplicationsWithRealtimePersistentLongrunningConnectionsWithSignalR.aspx]

To get SignalR up and running following are few todo’s on server side:

Step 1 is to create a PersistentConnection class like follows


Note that Connection.Broadcast would send the data to all connected clients. If you need to sent to a particular client you can use the Send method.

Send(string clientId, object value);

Note Send requires the intended clientId. If you were to be building a chat client or a custom push service, you probably would be storing clientId’s somewhere in a local object or a central repo.

Other useful functions that PersistantConnection class provides that can be overridden:




Step 2 is to add the routes if you are using MVC. This route needs to be registered in Global.asax


That’s pretty much it on the server side

Step 3, if the intended client is a web browser it’s as easy as follows:




That’s all is to SignalR setup. A chat type client would require some sort of client association on the server side to keep communication private.

But what about non-browser based apps, like a console app or a windows service. SignalR has libraries for those too, can be downloaded from NuGet.

In real world applications, no project ends up with a single instance, single class project. In real world apps, there are many class’s and class’s are initialized and disposed all the time. In this scenario opening and closing a SignalR connection or instializing a new SignalR object is a wrong approach since you want be connected to the server all time.

One way to keep the connection persistant is to create a static signalR object, in following case it’s a singleton class


A calling class can get an the instance of the above PushClass


Another way but fancier way to achieve the same persistant effect could be like follows:



The calling class can do the following:

Labels: ,