asp.net MVC implementation based on XMLHttpRequest long polling Comet

Source: Internet
Author: User
Tags current time


My personal understanding is that it looks like a client can subscribe to a server-side event in a Web environment that notifies the client via events. If the server side is implemented with ASP.net, you can take advantage of the. NET event-driven mechanism, which is interesting, as shown in the following sample code.

First look at the Web front-end JS code:

  code is as follows copy code

JQuery (function ($) {
    function long_polling () {
& nbsp;       $.getjson ('/comet/longpolling ', function (data) {
             if (DATA.D) {
                 $ (' #logs '). Append (DATA.D + "<br/>");
           }
            long_polling ();
       });
   }
    long_polling ();
});

The JS code is very simple, is a recursive call (called at callback), through the jquery $.getjson to launch the AJAX request, '/comet/longpolling ' represents the requested server Cometcontroller Longpolling Action URL. Here we can see that the difficulty of implementing Comet is not on the Web front end, but on the server side.

Next, focus on the Web server asp.net MVC Controller code.

The first thing to note is that in response to the XMLHttpRequest long polling request, we need to implement an asynchronous controller (Asynccontroller), and if you are unfamiliar with Asynccontroller, it is recommended that you read the article on MSDN Using An asynchronous Controller in ASP.net MVC.

First on the Controller implementation code:

(Note: The function that the controller implements is to send the server to the client every 5 seconds when time)

The code is as follows Copy Code

public class Cometcontroller:asynccontroller
{
Longpolling Action 1-processing client-initiated requests
public void Longpollingasync ()
{
Timer, 5 seconds to trigger a elapsed event
System.Timers.Timer Timer = new System.Timers.Timer (5000);
Tell ASP.net to do an asynchronous operation next
AsyncManager.OutstandingOperations.Increment ();
Subscribe to Timer Elapsed event
Timer. Elapsed + = (sender, E) =>
{
Save the arguments that will be passed to the longpollingcompleted
Asyncmanager.parameters["Now"] = E.signaltime;
Tells ASP.net that the asynchronous operation is complete and that the Longpollingcompleted method is called
AsyncManager.OutstandingOperations.Decrement ();
};
Start timer
Timer. Start ();
}

Longpolling Action 2-asynchronous processing completes, sending a response to the client
Public ActionResult longpollingcompleted (DateTime now)
{
Return Json (New {d = now. ToString ("Mm-dd HH:mm:ss") +
"--Welcome to cnblogs.com!"},
Jsonrequestbehavior.allowget);
}
}

Implementing an asynchronous controller requires inheriting System.Web.Mvc.AsyncController and breaking the action into two, such as Action called Longpolling, which is decomposed into longpollingasync and Longpollingcompleted. Longpollingasync accepts the client request and initiates an asynchronous operation, the asynchronous operation completes, and the longpollingcompleted is invoked.

AsyncManager.OutstandingOperations.Increment (); Tell ASP.net to do an asynchronous operation next.

AsyncManager.OutstandingOperations.Decrement (); Tells ASP.net that the asynchronous operation is complete, call the Longpollingcompleted () method.

The asynchronous operation in the

Sample code is to pass the server's current time as a parameter to the longpollingcompleted () method, longpollingcompleted () get the server's current time and pass it to the client, which is displayed when the client receives it. will continue to launch Ajax requests ... In this way, the Comet based on XMLHttpRequest long polling is implemented.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.