客户端ajax请求超时后,服务器在做什么?

在客户端的js脚本里面,设置请求超时时间为1s。超过一秒后调用xhr.abort,中断请求。
        /* 串行化一系列数据
         * 返回串行化后的字符串
         * @a=键/值 对的散列表
         * Date:20170118
         */
        function serialize(a) {
            var s = [];
            if (a.constructor == Array) {
                for (var i = 0; i < a.length; i++) {
                    s.push(a[i].name + "=" + encodeURIComponent(a[i].value));
                }
            }
            else {
                for (var i in a) {
                    s.push(i + "=" + a[i]);
                }
            }
            return s.join("&");
        }

        var data = {
            name:"ouyangna"
        };

        var xhr = new XMLHttpRequest();

        // 浏览器收到服务器响应
        xhr.onload = function () {
            console.log("listen server sounds.");
            console.log(xhr.responseText);
        };

        xhr.open("post", "http://localhost/WebApplication1/Default.aspx", true);

        var timeoutLength = 1000;
        var requestDone = false;

        // 检查文档的加载状态,文档的状态什么时候更新?
        xhr.onreadystatechange = function () {
            //数据加载完成,并且尚未超时。
            if (xhr.readyState == 4 && !requestDone) {
                console.log("requestDone:" + requestDone);
                console.log("data transfer over.")
                console.log(xhr.responseText);
                xhr = null;
            }
            if (requestDone) {
                xhr.abort();
                console.log(xhr.readyState);
                console.log("time out." + Date.now());
            }
            //
            if (xhr.readyState == 3) {
                console.log(xhr.responseText);
            }
        };

        // 从HTTP响应中解析数据
        // type=正确的值包括:xml script text html 默认是""
        function httpData(r, type) {
            var ct = r.getResponseHeader("content-type");

            var data = type == "xml" ? r.responseXML : r.responseText;

            if (type=="script") {
                eval.call(window, data);
            }

            return data;
        }

        // 设置请求头部
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        console.log("send");
        xhr.send(serialize(data));


        // 1s后执行回调函数,用于取消请求(如果请求尚未完成)
        setTimeout(function () {
            requestDone = true;
        }, timeoutLength);

在服务器端,编写运行时间超过1s的代码,观察服务器在1s的状态,发现:
在客户端请求超时后,http连接并没有断开,请求还在继续等待服务器返回,服务器最终返回状态为200
服务器代码:

   public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("aaaa");
            Thread.Sleep(6000);
            System.Diagnostics.Debug.WriteLine("server still in working."+DateTime.Now.ToLongTimeString());
            Response.Write("game over.");
        }
    }

 



因此,客户端和服务端必须同时设置超时机制。

posted @ 2017-01-19 13:52  viola  阅读(1627)  评论(0编辑  收藏  举报