Tuesday, August 26, 2008

Comet in ASP.Net

Comet, in general, is the technique of enabling server-side push instead of having client-side pull for refreshing information in the user's interface. The latter involves regular pinging of the server from the client to check for any changes that may have occurred on the server and send the corresponding information to update the user's UI accordingly. In applying Comet, one can notify the server-side changes to the client without the need of the constant pinging. Typical scenarios where Comet appears to have a relevant niche involve browser based chat applications, online collaboration and editing systems (such as GoogleDocs) and browser based web OSs.

Comet ties client-side JavaScript tightly with the server-side by having a long-running HTTP connection through which the server can push updates to the client as and when they occur. One technique that has worked well for me has been opening having one connection open in a hidden iframe on the page that's long-running. Another connection that sends information from the client up to the server is also established whenever corresponding user interaction takes place. This second connection opens and closes just like a regular HTTP request and can be performed using AJAX.

In an great example by Dave Ward at Encosia, he provides a very basic example of how the server can push data down to the client by using sleep states on the server. He performs a callback on the client by writing out pieces of JavaScript to the long-running connection, thus making it run within the iframe and, since its in the same domain, can call methods in the parent window to perform updates in the browser window. This and a number of other articles I read up elsewhere prompted me to try and use this technique in a real world application. The application I felt I could quickly demonstrate Comet was a chat application.

The image below shows the chat application in operation in two different browsers on the same machine. The example was written in Visual Web Developer 2008 using the Microsoft Dot Net Framework 3.5. The code works in FF2 and Opera 9.5 so far. Not too many optimizations have been performed as the goal of this was to just demonstrate a way in which Comet could work without having to switch to any "dedicated Comet" servers. The same principles could be applied in Java too where the two connections could be established with two separate servlets to achieve the same results. In case anyone would like to view the source code for this, email me at avinpr@yahoo.com.

Cheers.

No comments: