asp.net use Comet to develop an HTTP long connection sample sharing

Source: Internet
Author: User

 comet (Reverse AJAX) is primarily connected through an HTTP long connection, maintaining a connection to the server, implementing server PUSH and two-way communication, and following the example to learn how to use it

Benefits: 1. Save resources compared to Ajax polling, and latency is small, 2. Compared with websocket, the applicable scenarios are quite extensive.   1. First create an empty project for asp.net MVC   Add a controller   (the same code can be used in asp.net webform)     code is as follows: public class Cometc Ontroller:controller     {        public ActionResult Test ()         {            Response.Buffer = false;             while (true) )             {                Response.Write (datet Ime. Now.tostring ("Yyyy-mm-dd HH:mm:ss FFF") + "|");                 Thread.Sleep (500);                        //not running here             return Content ("");        }    } {  2. Build a controller and view to display the html    code as follows: public class Hom Econtroller:controller     {  &NBSp    //       //Get:/home/          public ActionResult Index ()         {            return View ()     &NBS    } P    }       View Code is more important     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 () &n Bsp      });           function GetData () {            Loadxmldoc ("/comet/test") ); &nbSp      }          //Create a XHR function Createrequest () {            if (window. XMLHttpRequest &&! (Window. ActiveXObject)) {                try {                    req = new XMLHttpRequest ();                } catch (e) {              &NB Sp     req = false;                        //branch for ie/windows ActiveX vers Ion               /else if window. ActiveXObject] {                try {req = new ActiveXObject ("Msxml2.xmlhttp"); catch (e) {                    try {        &NBS P           &nbsp   req = new ActiveXObject ("Microsoft.XMLHTTP");                    } catch (e) {          &NB Sp             req = false;                                   & nbsp {           /       }          //Initiating request Func tion Loadxmldoc (URL) {            try {              &N Bsp if (req) {                    Req.abort ()                     req = false;                                 Createre Quest ();                 if (req) {  &nbsp                 Req.onreadystatechange = Processreqchange;                     Req.open ("Get", url, True);                     req.send ("");                } else {                & nbsp   Alert (' Unable to create request ');                            } catch (e) {alert (E. message);        }          /Check Status function Processreqchange () {    &nbs P       if (req.readystate = 3) {                try {  &NBSP ;                 ProcessInput (Req.responsetext);                     if (Req.responseText.length > 3000) {                        L Astdelimiterposition =-1; GetData ();                                   & nbsp }                 catch (e) {              &NB Sp     alert (e.message);                            }                    //split string function ProcessInput (input) {        &NB Sp   var text = input;             var nextdelimiter = text.indexof (' | ', Lastdelimiterposition + 1);             if (Nextdelimiter!=-1) {              &NBS P 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> </head> <body>     <div>   &N Bsp     <div id= "Div1" >         </div>         <div id= "Div2" >         </div>     </div> </body> </html>       3. The final effect is:   on the page to display a time, every half a second update aTimes     Of course, when you get the content, you do what you want to do ... Update Dom or execute JS, (OK with Eval this method ~ ~)   4. This example is just an implementation based on asynchronous JavaScript,   is actually available through <iframe> and <script> These two tags are implemented, especially the script tags 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.