Use ASP. net mvc to implement comet Based on XMLHttpRequest long polling

Source: Internet
Author: User

Previously, in "reverse Ajax, Part 1: Introduction to Comet" (English version)ArticleI learned the "multipart XMLHttpRequest-based Comet" knowledge, and then implemented it using ASP. NET MVC. For details, see implementing comet Based on multipart XMLHttpRequest using ASP. NET MVC.

Today I continue to learn about the comet Based on XMLHttpRequest long polling and implement it using ASP. net mvc. I will share it in this article.

What is XMLHttpRequest long polling?

This is a recommended way to implement Comet. Open an Ajax request to the server and wait for a response. The server needs some specific functions to allow the request to be suspended. when an event occurs, the server sends a response to the pending request and closes the request. Then the client uses this response and opens a new long-lived Ajax request to the server.

This is a recommended method to implement comet is to open an Ajax request to the server and wait for the response. the server requires specific features on the server side to allow the request to be suincluded. as soon as an event occurs, the server sends back the response in the suincluded request and closes it. the client then consumes the response and opens a new long-lived Ajax request to the server.

In my personal understanding, it seems like a client can subscribe to server events in a web environment, and the server notifies the client through events. If the server is implemented using ASP. NET, you can use the. NET event-driven mechanism. This is very interesting. The following exampleCodeThis is displayed.

First look at the Web Front-end JS Code:

 
Jquery (Function($ ){
FunctionLong_polling (){
$. Getjson ('/Comet/longpolling ',Function(Data ){
If(Data. d ){
$ ('# Logs'). append (data. d + "<br/> ");
}
Long_polling ();
});
}
Long_polling ();
});

The js code is simple, that is, a recursive call (called during callback), through jquery's $. getjson initiates an Ajax request. '/Comet/longpolling' indicates the URL of the longpolling action of the requested server cometcontroller. Here we can see that the difficulty of implementing comet is not the Web Front-end, but the server side.

Next we will 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). If you are not familiar with asynccontroller, read the document using an asynchronous controller in ASP on msdn. net MVC.

First, go to the controller implementation code:

(Note: The Controller implements the function of sending the server time to the client every five seconds)

 Public   Class Cometcontroller: asynccontroller
{
// Longpolling Action 1-process client-initiated requests
Public Void Longpollingasync ()
{
// Timer, triggering an elapsed event in 5 seconds
System. Timers. Timer timer = New System. Timers. Timer ( 5000 );
// Tell ASP. NET that an asynchronous operation will be performed next
Asyncmanager. outstandingoperations. increment ();
// Subscribes to the elapsed event of the timer.
Timer. elapsed + = (sender, e) =>
{
// Save the parameter to be passed to longpollingcompleted
Asyncmanager. Parameters [ " Now " ] = E. signaltime;
// Indicates that the ASP. NET asynchronous operation has been completed and longpollingcompleted method is called.
Asyncmanager. outstandingoperations. decrement ();
};
// Start Timer
Timer. Start ();
}

// Longpolling Action 2-asynchronous processing is complete, send 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 );
}
}

To implement an asynchronous controller, you must inherit system. Web. MVC. asynccontroller and divide the action into two types. For example, if the action is longpolling, it is divided into longpollingasync and longpollingcompleted. Longpollingasync accepts client requests and initiates asynchronous operations. After asynchronous operations are completed, longpollingcompleted is called.

Asyncmanager. outstandingoperations. increment (); tells ASP. NET that an asynchronous operation will be performed 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 current time of the server as a parameter to the longpollingcompleted () method. longpollingcompleted () gets the current time of the server and passes it to the client. After receiving the time, the client displays it, will continue to initiate Ajax requests... in this way, the comet is implemented based on XMLHttpRequest long polling.

The running result of the sample code is as follows:

Summary

I used to think that comet is a very advanced thing. After I did it myself, I found it was not that difficult. Therefore, it is important to do it first!

If you cannot do this in a project, write a blog!

Code download

Cometmvcdemo_longpolling.rar

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.