What is comet?
Comet is a Web application model in which a long-held HTTP request allows a web server to push data to a browser, without the browser explicitly requesting it. (from wiki)
Comet is a server push technology based on HTTP persistent connections (from IBM developerworks ).
What is multipart XMLHttpRequest?
It is a method for bundling multiple HTTP requests into a single HTTP request and unbundling on the client side through a javascript handler. (from Alibaba magicians blog)
Chinese solution: it allows the client to transmit multiple resources from the server to the client using only one HTTP Request (from gulangyu-front-end blog ).
Why ASP. net mvc?
I learned "reverse Ajax, Part 1: Introduction to Comet" yesterday,CodeThe server code uses Java. To better understand this part of knowledge, we can use ASP. net mvc to implement a comet based on multi-part XMLHttpRequest.
Is it practical?
To be honest, there is no practical value, just for learning. There are too few browsers that support multipart XMLHttpRequest. Currently, only Firefox is supported. Chrome and ie9 are not supported.
Sample Code
1. Front-end JavaScript code
VaRXhr = $. ajaxsettings. xhr ();
Xhr. multipart =True;
Xhr. Open ('get', '/Comet/multipart ',True);
Xhr. onreadystatechange =Function(){
If(Xhr. readystate = 4 ){
$ ('# Logs'). append (xhr. responsetext + "<br/> ");
}
};
Xhr. Send (Null);
The key code is xhr. multipart = true;
2. Server ASP. net mvc controller code
Public Class Cometcontroller: Controller
{
// End mark, which is randomly generated
Static String Boundary = " Abcdefghijklmnopqrst " ;
Public Actionresult multipart ()
{
Response. contenttype = " Multipart/X-mixed-replace; boundary = \" " + Boundary +" \" " ;
Response. headers. Add ( " Connection " , " Keep-alive " );
Response. Output. Write ( " -- " + Boundary );
Response. Flush ();
// Send data to the client every 5 seconds
While ( True )
{
// The MIME type of the data sent to the client. If it is JSON, the application/JSON
// Note that writeline () must be used here ()
Response. Output. writeline ( " Content-Type: plain/Text " );
// No less code is required for generating empty lines.
Response. Output. writeline ();
Response. Output. writeline (datetime. Now. tostring ( " Hh: mm: Ss. fff " ));
// The sending end flag indicates that the client has completed sending
Response. Output. writeline ( " -- " + Boundary );
Response. Flush ();
System. Threading. thread. Sleep ( 5000 );
}
}
}
Although the above Code looks simple, it still took some twists and turns during debugging.
Code download
Cometmvcdemo.rar
You need to runProgram(An error will be reported when running on the built-in web server in vs2010 ). When multipartxhr.htm, the server time is displayed in 5 seconds.