Update time Asp. net USES Comet to develop http long connection sample sharing

  • 2020-11-20 06:03:15
  • OfStack

Benefits :1. Resource savings and less latency compared to AJAX polling, 2. Compared to webSocket, it is applicable to a wide range of scenarios.

1. First create an Asp.net MVC empty project

Add 1 controller (the same code is available in ES10en.net WebForm)


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);
            }
            // It's not gonna get here 
            return Content("");
        }
    }
}

2. Build another controller and View to display HTML


public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }
    }

The View code is important


@{
    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");
        }
        // new 1 a 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;
                    }
                }
            }
        }
        // The initiating 
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 > 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);
                }
            }
        }
        // The output   Or what event is triggered 
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 effect is:

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

Of course, once you get the content, you can actually do whatever you want... Either update DOM or execute js (thanks to the eval method ~~).

4. This example is just one implementation of asynchronous Javascript,

We can actually pass it < iframe > and < script > These two tags do the implementation, in particular the script tag can access and execute the cross-domain javascript


Related articles: