zoukankan      html  css  js  c++  java
  • 轮询与长轮询 浅析

    轮询:说白了就是客户端定时去请求服务端,  是客户端主动请求来促使数据更新;

    长轮询:说白了 也是客户端请求服务端,但是服务端并不是即时返回,而是当有内容更新的时候才返回内容给客户端,从流程上讲,可以理解为服务器向客户端推送内容;

    从中大家可以看出区别:

    轮询:

    1:大量耗费服务器内存和宽带资源,因为不停的请求服务器,很多时候 并没有新的数据更新,因此绝大部分请求都是无效请求

    2:数据不一定是实时更新,要看设定的请求间隔,基本会有延迟。

    长轮询:

    1:解决了轮询的两个大问题,数据实时更新;

    2:唯一的缺点是服务器在挂起的时候比较耗内存;

    总体而言,比轮询进步了一大大大步

    废话不多说,上代码(最简单的小例子)

    客户端

    <body>
        <label id="lbLongPolling"></label>
        <br />
        <label id="lbNoLongPolling"></label>
        <script>
            $(function () {
               //长轮询,请求服务端,等到响应了,再次请求
                var SendLongPolling = function () {
                    $.get("../Home/LongPolling", function (data) {
                        debugger;
                        $("#lbLongPolling").html("长轮询:" + data);
                        SendLongPolling();
                    });
                };
                SendLongPolling();
    
    
                //轮询,不管三七21,每隔1秒就请求一次
                setInterval(function () {
                    debugger;
                    $.get("../Home/NoLongPolling", function (data) {
                        debugger;
                        $("#lbNoLongPolling").html("轮询:" + new Date().toLocaleString());
                    });
                }, 1000);
            })
        </script>
    </body>
    View Code

    服务端:

            /// <summary>
            /// 长轮询,模拟挂起的操作,服务器每秒会有更新,然后返回给客户端实时数据
            /// </summary>
            /// <returns></returns>
            public ActionResult LongPolling()
            {
                while (true)
                {
                    Thread.Sleep(1000);
                    return Content(DateTime.Now.ToString());
                }
            }
    
            /// <summary>
            /// 轮询,只要客户端请求就返回数据
            /// </summary>
            /// <returns></returns>
            public ActionResult NoLongPolling()
            {
                return Content(DateTime.Now.ToString());
            }
    View Code

    例子虽然小,但是应该看得比较清楚了,服务端挂起的那里 也许模拟的不太好,期待园友们指正交流!

     效果图

  • 相关阅读:
    Leetcode#179 Largest Number
    Leetcode#155 Min Stack
    Leetcode#14 Longest Common Prefix
    Leetcode#101 Symmetric Tree
    Leetcode#172 Fractorial Trailing Zero
    Leetcode#28 Implement strStr()
    Leetcode#46 Permutations
    Leetcode#48 Rotate Image
    Leetcode#134 Gas station
    Leetcode#137 Single Number II
  • 原文地址:https://www.cnblogs.com/wolfworker/p/7346625.html
Copyright © 2011-2022 走看看