<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Clay Lenhart's Blog &#187; Comet</title>
	<atom:link href="http://clay.lenharts.net/blog/tag/comet/feed/" rel="self" type="application/rss+xml" />
	<link>http://clay.lenharts.net/blog</link>
	<description>A blog on .Net and SQL Server</description>
	<lastBuildDate>Tue, 31 Oct 2017 10:34:08 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.2.2</generator>
	<item>
		<title>WebSockets is cool, but what can you do today?</title>
		<link>http://clay.lenharts.net/blog/2010/10/19/websockets-is-cool-but-what-can-you-do-today/</link>
		<comments>http://clay.lenharts.net/blog/2010/10/19/websockets-is-cool-but-what-can-you-do-today/#comments</comments>
		<pubDate>Tue, 19 Oct 2010 19:05:48 +0000</pubDate>
		<dc:creator><![CDATA[Clay Lenhart]]></dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[Ajax]]></category>
		<category><![CDATA[ASP.Net MVC]]></category>
		<category><![CDATA[Comet]]></category>
		<category><![CDATA[Web Application]]></category>
		<category><![CDATA[WebSockets]]></category>

		<guid isPermaLink="false">http://clay.lenharts.net/blog/?p=136</guid>
		<description><![CDATA[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. <a href="http://clay.lenharts.net/blog/2010/10/19/websockets-is-cool-but-what-can-you-do-today/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>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&#8217;t much support, both in browsers and on the server in IIS and ASP.Net.  </p>
<p>Today you can use a <a href="http://en.wikipedia.org/wiki/Comet_%28programming%29">Comet technique</a> (in particular, <a href="http://en.wikipedia.org/wiki/Comet_%28programming%29#Ajax_with_long_polling">Ajax with long polling</a>) 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.<br />
<span id="more-136"></span></p>
<p>On the server, there are two resource limits to consider with IIS and ASP.Net:</p>
<ul>
<li>HTTP request limits &#8212; in IIS7 the default limit is 5000</li>
<li>ASP.Net thread limits &#8212; in IIS7 the default limit is 12 x number of CPUs </li>
</ul>
<p>For a typical ASP.Net application (and ASP.Net MVC application), an HTTP request always uses an ASP.Net thread.  However you can use <a href="http://msdn.microsoft.com/en-us/magazine/cc163725.aspx">Asynchronous Pages in ASP.Net</a> or <a href="http://msdn.microsoft.com/en-us/library/ee728598.aspx">Asyncronous Controllers in ASP.Net MVC</a> to free the ASP.Net thread (but still keep the HTTP request). Using Asynchronous Pages or Controllers is ideal for Comet HTTP requests.</p>
<p>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.</p>
<pre class="brush: jscript; title: ; notranslate">
        $(function () {
            checkEmail();
        });

        function checkEmail() {
            $.post(&quot;/CheckEmail&quot;, null, function (data, s) {
                if (data.d) {
                    $('#emailCheck').text('You have mail!');
                } else {
                    $('#emailCheck').text('No change.');
                }

                checkEmail();
            });
        }
</pre>
<p>On the server, the code uses the AsyncController to free the ASP.Net thread for other HTTP requests until this HTTP request has completed.</p>
<pre class="brush: csharp; title: ; notranslate">
    public class CheckEmailController : AsyncController
    {
        //
        // GET: /CheckEmail/

        public void IndexAsync()
        {
            AsyncManager.OutstandingOperations.Increment();
            MyAsyncEmailChecker.CheckForEmailAsync(hasEmail =&gt;
            {
                AsyncManager.Parameters[&quot;hasEmail&quot;] = hasEmail;
                AsyncManager.OutstandingOperations.Decrement();
            });
        }

        private class IndexResponse
        {
            public bool d { get; set; }
        }

        public JsonResult IndexCompleted(bool hasEmail)
        {
            return this.Json(new IndexResponse() { d = hasEmail });
        }

    }
</pre>
<p>There are three phases on the server. </p>
<pre class="brush: csharp; title: ; notranslate">
        public void IndexAsync()
        {
            AsyncManager.OutstandingOperations.Increment();
            MyAsyncEmailChecker.CheckForEmailAsync(/* callback function */);
        }
</pre>
<p>The first phase calls AsyncManager.OutstandingOperations.Increment() and MyAsyncEmailChecker.CheckForEmailAsync.  When AsyncManager.OutstandingOperations is zero, the matching &#8220;Completed&#8221; 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. &#8220;Async&#8221; functions are common in the .Net framework, for example:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/k0syd8kf.aspx">MessageQueue.BeginReceive</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/aa719796%28VS.71%29.aspx">Asynchronous Webservice calls</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.beginsend.aspx">Socket.BeginSend</a></li>
</ul>
<pre class="brush: csharp; title: ; notranslate">
            /* an Async function */(hasEmail =&gt;
            {
                AsyncManager.Parameters[&quot;hasEmail&quot;] = hasEmail;
                AsyncManager.OutstandingOperations.Decrement();
            })
</pre>
<p>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().</p>
<pre class="brush: csharp; title: ; notranslate">
        public JsonResult IndexCompleted(bool hasEmail)
        {
            return this.Json(new IndexResponse() { d = hasEmail });
        }
</pre>
<p>The IndexCompleted method returns the data to the browser &#8212; in this case it is a JsonResult.</p>
<p>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.</p>
<p>UPDATE 2011-05-20: You can download the full source code <a href="http://clay.lenharts.net/blog/wp-content/uploads/MvcAsyncTest.zip">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://clay.lenharts.net/blog/2010/10/19/websockets-is-cool-but-what-can-you-do-today/feed/</wfw:commentRss>
		<slash:comments>97</slash:comments>
		</item>
	</channel>
</rss>
