Page interval: half a second update time Asp.net use Comet to develop http persistent connection example sharing

Source: Internet
Author: User

Benefits: 1. Resource Saving and low latency compared with AJAX polling. 2. Compared with webSocket, it is widely used.

1. Create an empty Asp.net MVC project first

Add a controller (the same code can also be used in Asp.net WebForm)

Copy codeThe Code is 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 );
}
// Cannot run here
Return Content ("");
}
}
}

2. Create a controller and View to display HTML

Copy codeThe Code is as follows:
Public class HomeController: Controller
{
//
// GET:/Home/

Public ActionResult Index ()
{
Return View ();
}

}

View code is important

Copy codeThe Code is as follows:
@{
Layout = null;
}
<! DOCTYPE html>
<Html>
<Head>
<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 an 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;
}
}
}
}

// Initiate 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 the status
Function processReqChange (){
If (req. readyState = 3 ){
Try {
ProcessInput (req. responseText );
If (req. responseText. length & gt; 3000 ){
LastDelimiterPosition =-1; getData ();
}
}
Catch (e ){
Alert (e. message );
}
}
}


// Split the 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 triggered events
Function ProcessTime (time ){
Document. getElementById ('div1 '). innerHTML = time;
}
</Script>
</Head>
<Body>
<Div>
<Div id = "div1">
</Div>
<Div id = "div2">
</Div>
</Div>
</Body>
</Html>

3. The final result is:

A time is displayed on the page, updated every half second

Of course, after you get the content, you can do what you want... Update DOM or execute js. (fortunately, the eval method is used ~~)

4. This example is just an implementation based on Asynchronous Javascript,

In fact, you can also use the <iframe> and <script> labels. In particular, the script tag can access and execute cross-domain javascript.

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.