Benefits: 1. Save resources compared to Ajax polling, and latency is small, 2. Compared with websocket, the applicable scenarios are quite extensive.
1. Create an empty project for asp.net mvc first
Add a controller (the same code can be used in asp.net webform)
Copy Code code as follows:
public class Cometcontroller:controller
{
Public ActionResult Test ()
{
Response.Buffer = false;
while (true)
{
Response.Write (DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss FFF") + "|");
Thread.Sleep (500);
}
I can't run here.
Return Content ("");
}
}
}
2. Build another controller and view for displaying HTML
Copy Code code as follows:
public class Homecontroller:controller
{
//
Get:/home/
Public ActionResult Index ()
{
return View ();
}
}
The code for the view is more important
Copy Code code as follows:
@{
Layout = null;
}
<! DOCTYPE html>
<title>Index</title>
<script type= "Text/javascript" src= "Http://code.jquery.com/jquery-1.7.1.min.js" ></script>
<script language= "JavaScript" >
var req = false;
var lastdelimiterposition =-1;
$ (document). Ready (function () {
GetData ();
});
function GetData () {
Loadxmldoc ("/comet/test");
}
Create a new XHR
function Createrequest () {
if (window. XMLHttpRequest &&! (Window. ActiveXObject)) {
try {
req = new XMLHttpRequest ();
catch (e) {
req = false;
}//Branch for Ie/windows ActiveX version
else if (window. ActiveXObject) {
try {req = new ActiveXObject ("Msxml2.xmlhttp");} catch (e) {
try {
req = new ActiveXObject ("Microsoft.XMLHTTP");
catch (e) {
req = false;
}
}
}
}
Initiating a request
function Loadxmldoc (URL) {
try {
if (req) {
Req.abort ();
req = false;
}
Createrequest ();
if (req) {
Req.onreadystatechange = Processreqchange;
Req.open ("Get", url, True);
Req.send ("");
} else {
Alert (' Unable to create request ');
}
catch (E) {alert (e.message);}
}
Check Status
function Processreqchange () {
if (req.readystate = = 3) {
try {
ProcessInput (Req.responsetext);
if (Req.responseText.length > 3000) {
Lastdelimiterposition =-1; GetData ();
}
}
catch (e) {
alert (e.message);
}
}
}
Split string
function ProcessInput (input) {
var text = input;
var nextdelimiter = text.indexof (' | ', Lastdelimiterposition + 1);
if (Nextdelimiter!=-1) {
var timeStamp = text.substring (nextdelimiter + 1);
if (Timestamp.length > 0) {
Lastdelimiterposition = Nextdelimiter;
Processtime (TimeStamp);
}
}
}
Output or trigger what event
function Processtime (time) {
document.getElementById (' Div1 '). InnerHTML = time;
}
</script>
<body>
<div>
<div id= "Div1" >
</div>
<div id= "Div2" >
</div>
</div>
</body>
3. The final effect is:
Display a time on the page, updated every half second
Of course, when you get the content, you actually do whatever you want ... Update the DOM, or execute JS or, (fortunately, the Eval method ~ ~)
4. This example is just an implementation based on asynchronous JavaScript,
Can actually also be implemented through the <iframe> and <script> tags, especially if the script tag can access and execute Cross-domain javascript