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 () {
            checkEmail();
        });

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

                checkEmail();
            });
        }

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()
        {
            AsyncManager.OutstandingOperations.Increment();
            MyAsyncEmailChecker.CheckForEmailAsync(hasEmail =>
            {
                AsyncManager.Parameters["hasEmail"] = hasEmail;
                AsyncManager.OutstandingOperations.Decrement();
            });
        }

        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()
        {
            AsyncManager.OutstandingOperations.Increment();
            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;
                AsyncManager.OutstandingOperations.Decrement();
            })

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.

73 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.

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>