WebSockets is cool, but what can you do today?

WebSockets is a new feature that appears to be a great way to send messages from the server to the browser, however today there isn’t much support, both in browsers and on the server in IIS and ASP.Net.

Today you can use a Comet technique (in particular, Ajax with long polling) which is available in all browsers. Using this concept, the browser makes a standard AJAX call to the server that waits until it receives a message. Asynchronous Pages and Asynchronous Controller allow you to have long running HTTP requests without using precious ASP.Net threads.

On the server, there are two resource limits to consider with IIS and ASP.Net:

  • HTTP request limits — in IIS7 the default limit is 5000
  • ASP.Net thread limits — in IIS7 the default limit is 12 x number of CPUs

For a typical ASP.Net application (and ASP.Net MVC application), an HTTP request always uses an ASP.Net thread. However you can use Asynchronous Pages in ASP.Net or Asyncronous Controllers in ASP.Net MVC to free the ASP.Net thread (but still keep the HTTP request). Using Asynchronous Pages or Controllers is ideal for Comet HTTP requests.

Take for example an email web application that has jQuery code to check for new mail. It calls /CheckEmail which returns either true or false. As soon as it completes it calls checkEmail() immediately so that it can be notified of any new mail.

        $(function () {

        function checkEmail() {
            $.post("/CheckEmail", null, function (data, s) {
                if (data.d) {
                    $('#emailCheck').text('You have mail!');
                } else {
                    $('#emailCheck').text('No change.');


On the server, the code uses the AsyncController to free the ASP.Net thread for other HTTP requests until this HTTP request has completed.

    public class CheckEmailController : AsyncController
        // GET: /CheckEmail/

        public void IndexAsync()
            MyAsyncEmailChecker.CheckForEmailAsync(hasEmail =>
                AsyncManager.Parameters["hasEmail"] = hasEmail;

        private class IndexResponse
            public bool d { get; set; }

        public JsonResult IndexCompleted(bool hasEmail)
            return this.Json(new IndexResponse() { d = hasEmail });


There are three phases on the server.

        public void IndexAsync()
            MyAsyncEmailChecker.CheckForEmailAsync(/* callback function */);

The first phase calls AsyncManager.OutstandingOperations.Increment() and MyAsyncEmailChecker.CheckForEmailAsync. When AsyncManager.OutstandingOperations is zero, the matching “Completed” method is called. This increment prevents the Completed method from being called before the data is ready. Next the code initiates an Async call to MyAsyncEmailChecker.CheckForEmailAsync(). This is a method I wrote, and in fact it just a demo class for this article. It returns immediately and then calls the callback function 5 seconds later. “Async” functions are common in the .Net framework, for example:

            /* an Async function */(hasEmail =>
                AsyncManager.Parameters["hasEmail"] = hasEmail;

The next phase calls the function passed in when the MyAsyncEmailChecker finishes. It sets the return data in the AsyncManager.Parameters collection. These are the same parameters found in the IndexCompleted method. Next the code calls AsyncManager.OutstandingOperations.Decrement(). Now that AsyncManager.OutstandingOperations is zero, ASP.Net MVC will call IndexCompleted().

        public JsonResult IndexCompleted(bool hasEmail)
            return this.Json(new IndexResponse() { d = hasEmail });

The IndexCompleted method returns the data to the browser — in this case it is a JsonResult.

Lastly, most browsers limit 2 HTTP connections to the same server, though recent browsers do not have this limitation. If the browser has a long running HTTP connection to recent messages from the server, it is using one of your two HTTP connections.

UPDATE 2011-05-20: You can download the full source code here.

About Clay Lenhart

I am a DBA/Technical Architect for Latitude Group and love technology.
This entry was posted in ASP.Net and tagged , , , , , . Bookmark the permalink.

97 Responses to WebSockets is cool, but what can you do today?

  1. は私にあなたが批判のすべてをチェックアウトするために時間がかかったが、私は実際に作品を楽しみました。それは私にとって非常に有用であることが証明されたと私はここにすべてのコメンターに確信しています!それはあなたがいないだけに通知されることが可能であるときは、常に巨大なのですが、また従事します!私はあなたが楽しい書き込みこの書き込みアップを持っていた確信しています。

  2. 私はまったく同じ同じを持つ複数の電子メールを取得し、今「新しいコメントが追加された時に通知する」チェックボックスやコメントが追加されるたびに、クリックしました。そのサービスから私を削除あなたがすることができます、それはすることが可能であることができます方法はありますか?乾杯!

  3. はちょうどあなたが知っているように、このコンテンツが私のスマートフォンから少し奇妙に見えます。誰が、おそらくそれはちょうど私の携帯電話であることを知っています。ところで偉大なポスト。

  4. 私は本当に賞仕事のあなたの部分、優秀ポストを。所有者の{| ウェブログこのから取得かなりたくさん する必要が |

  5. ブラックオプスゾンビを取る[…] …利用できるようになりました見るここで[…] …

  6. 、私はあなたのサイトが、私はまた、テーマを愛する私はこの問題のためにヤフーを検索したときに、私はあなたのコンテンツが実際に有用であると言って持って誤って見つかったその驚くべき!私は現時点では、すべての記事を読むために、その多くの時間を持っていけないが、私はそれをブックマークし、また、あなたのRSSフィードを追加しました。私は一日か二日で戻ってきます。偉大なウェブサイトをありがとう。

  7. いくつかの本当に品質ブログ私のブックマークに保存し、インターネットサイトサイト |このインターネットウェブのポスト。この中に入れている| あなたがいることをすべてのあなたの努力のための

  8. First off I would like to say excellent blog! I had a quick question in which I’d like to ask if you don’t mind. I was curious to know how you center yourself and clear your thoughts before writing. I’ve had a hard time clearing my thoughts in getting my thoughts out there. I truly do take pleasure in writing but it just seems like the first 10 to 15 minutes are lost just trying to figure out how to begin. Any ideas or hints? Kudos!

  9. Joanne Ball says:

    Kevin had been completely over his go, forging the future regarding his father’s company without having oversight, and really, without a sturdy concept: “At the time, we didn’t really know what we were going to make, at what price details, [and] at what price. ” Kevin Lee was building a total electronics product line in secret before he had the business partnership to do anything with that. He was making Is better than By Dre before Dre explained he was allowed. And he was panicking. “It was beyond insubordination, ” says Kevin. “[I was going to] lose the trust of my father. I already had huge amount of money of inventory. He would have mortally wounded me. “

  10. Remember to watertight elder scrolls online gold utilization of the concern pack.

  11. Admiring the time and effort you put into your website and in depth information you offer. It’s nice to come across a blog every once in a while that isn’t the same old rehashed material. Fantastic read! I’ve bookmarked your site and I’m adding your RSS feeds to my Google account.

  12. I has been suggested this locate from end to end my personal cousin. I’m not selected whether this submit is printed with him as rejection one as well take in such exacting approximately our problem. You’re incredible! Thank a person!

  13. Every weekend i used to visit this site, for the reason that i wish for enjoyment, for the reason that this this web page conations truly pleasant funny data too.

  14. If you are going for finest contents like myself, just visit this website all the time for the reason that it offers quality contents, thanks

  15. please pay a visit to the websites we stick to, which includes this a single, because it represents our picks through the web

  16. Great remarkable issues here. I am very happy to peer your article. Thank you a lot and i’m taking a look ahead to touch you. Will you please drop me a e-mail?

  17. Chloe Quinn says:

    There is apparently a bundle to realize about this. I think you made various good points in features also.

  18. You have mentioned very interesting details ! ps decent site. “Ask me no questions, and I’ll tell you no fibs.” by Oliver Goldsmith.

  19. There are actually quite a lot of particulars like that to take into consideration. That may be a nice level to carry up. I supply the thoughts above as general inspiration but clearly there are questions just like the one you bring up where a very powerful thing will likely be working in honest good faith. I don?t know if greatest practices have emerged around things like that, but I’m positive that your job is clearly identified as a fair game. Both boys and girls feel the impression of just a second

  20. You have mentioned very interesting details ! ps decent site. “Ask me no questions, and I’ll tell you no fibs.” by Oliver Goldsmith.

  21. Robert Scott says:

    You’re so interesting! I don’t believe I’ve read anything like that before. So wonderful to discover somebody with original thoughts on this topic. Really.. thanks for starting this up. This website is something that is needed on the web, someone with a little originality!

  22. James Avery says:

    To illustrate, a report in Journal of Investigative Dermatology points out that the skin can actually use circulating cholesterol to make the hormone androgen. Laser resurfacing can be done in the dermatologist office instead of a hospital so that provides a much greater financial savings.

  23. Shani Doig says:

    I’ll right away snatch your rss as I can not in finding your email subscription hyperlink or newsletter service. Do you’ve any? Please let me know in order that I could subscribe. Thanks.

  24. [url=http://www.newkakaku.com/xinq6.htm]上品なブランドの新作が期間限定セール発売上品なルイヴィトン、グッチやエルメスなどのブランドコピーの新作が大量入荷しました。種類が豊富で、勝手に選べます。激安の上に、品質には保証があって、末長くご愛用いただけます。新年とクリスマスを迎えで、期間限定セールが開催中で、早く手に入れましょう。[/url]

  25. [url=http://www.brandiwc.com/brand-super-9-copy-0.html]ウブロスーパーコピー時計のその 36 の連続した日の旅行の帳簿の名で満ちています。 0.127493074 1.最も合理的な価格で商品を消費者に提供致します。2.弊社のウブロ時計商品品数大目で、商品は安めです!商品現物写真。4.数量制限無し、一個の注文も、OKです。 . 0.764525914 スーパーコピー時計. 、安心、安全にお届けします.品数 豊富な商商品数も大幅に増え、品質も大自信です[/url]

  26. [url=http://www.ooobrand.com/aq/index.html]ヴィトンのダミエ財布N62668コピー商品です。イタリアのリゾート地リビエラの海と砂をイメージして作られたダミエアズールシリーズ。中でも男女問わず絶大な支持を集めているのがこの「ジッピーウォレット」。機能的なラウンドファスナー開閉式、多種多様な用途に対応した内部様式、シンプルで無駄のないデザイン等、いい所を挙げたらキリがない程のマストアイテム。普段使いには勿論、海外旅行時も考慮された仕様になっているので、インターナショナル派の貴方も大満足間違いなしです。弊社のサイトでは、シリーズごとに品番などをご覧にくださいで、ご自身にマッチしたルイヴィトンスーパーコピー商品を探しにご活用ください。[/url]

  27. [url=http://www.newkakaku.com/lxq8.htm]ブランド 時計 激安 ブランド 腕時計ブランドコピーの6年老舗、スーパーコピー商品、ブランドスーパーコピー最新作、ルイ ヴィトンコピー、エルメスコピー、シャネルコピー、グッチコピー、ブルガリコピー、プラダ コピー、ロレックスコピー、腕時計コピー、バッグコピー、財布コピー、アクセサリーコピーこちらはブランドスーパーコピー代引き、コピーブランド通販です。主にコピーブランド 時計,コピーブランドバック,コピーブランド 財布,大阪コピーブランドを取り扱っております 。韓国 コピーブランド、信頼できるNランク鶴橋 コピーブランド 専門[/url]

  28. I love reading your websites. thnx!

  29. Pingback: How to do long-polling AJAX requests in ASP.NET MVC? [duplicate] - QuestionFocus

  30. Brittanie says:

    Hello, this weekend is pleasant for me, for the reason that this occasion i am reading this fantastic informative piece of writing here at my residence.|

  31. This is a topic that’s close to my heart… Thank you! Where aree your contact details though?

  32. スーパーコピーブランド

    ルイヴィトンコピー、 ミョウミョウコピー、シャネルコピー、エルメスコピー品格安通販。
    商品は全て最高な材料 と優れた技術で造られて、正規と比べて、品質が無差別です,製品は、高品質と低価格で提供されています。
    また何かあればよろしくお願いいたします。【送料無料】エルメス スカーフをセール価格で販売中♪エルメス スカーフ カレ90 シルク100% グリーン系 新品 雪の結晶 クリスマス ヒイラギ レディース HERMES記載通りで満足。大変安く入手できました。綺麗な品でした。

  33. 日本な人気と信頼スーパーブランドコピー専門店
    —————- —————– —————- —————
    ■経営する商品:バッグ、財布、腕時計 その他小物。
    —————- —————– —————- —————
    コーチ、ロレックス、プラダ、 ディオール、
    —————- —————– —————- —————
    —————- —————– —————- —————

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>