美文网首页
long polling 2023-02-23

long polling 2023-02-23

作者: 9_SooHyun | 来源:发表于2023-02-22 19:57 被阅读0次

    长轮询 polling

    场景

    client需要监听server的某个事件(比如更新),事件发生后做相应的动作

    标准轮询

    最朴素的做法是client进行standard polling:
    HTTP Polling consists of a client, for example, a web browser, continually asking a server for updates.

    client不断地、主动地轮询server目标事件是否发生。server处理每个请求并即时d返回

    standard polling

    There are downsides to this “standard” HTTP polling:

    There is no perfect time between requests for updates. Requests will always be either too frequent (and inefficient) or too slow (and updates will take longer than required).

    As you scale, and the number of clients increases, the number of requests to the server also increases. This potentially becomes inefficient and wasteful as resources are used without purpose.

    那么,能不能做成像回调那样呢?等server发生事件,才去通知client

    长轮询

    回调的核心,是向事件发生方注册一个消息通知的通道

    我们常说的回调函数,本质上就是一个消息通道

    HTTP Long Polling is a variation of standard polling that emulates a server pushing messages to a client (or browser) efficiently. 基于HTTP的长连接,是一种通过长轮询方式实现"服务器推"的技术
    这个长http连接本身,就是向server注册的消息通道,和编程中的回调函数一个作用

    长轮询的实现

    Web applications were originally developed around a client/server model, where the Web client is always the initiator of transactions, requesting data from the server. Thus, there was no mechanism for the server to independently send or push data to the client without the client first making a request.

    To overcome this deficiency, Web app developers can implement a technique called HTTP long polling, where the client polls the server requesting new information. The server holds the request open until new data is available. Once available, the server responds and sends the new information. When the client receives the new information, it immediately sends another request, and the operation is repeated.

    long polling

    This is much more efficient than regular polling.

    The browser will always receive the latest update when it is available

    The server is not inundated with requests that will never be fulfilled.

    How long is a long poll?

    In the real world, any client connection to a server will eventually time out. How long the server will hold the connection open before it responds will depend on several factors: The server protocol implementation, server architecture, the client headers and implementation (in particular the HTTP Keep-Alive header), and any libraries that are used to initiate and maintain the connection.

    Of course, any number of external factors can also affect the connection, for example, a mobile browser is more likely to temporarily drop the connection as it switches between a WiFi and cellular connection.

    以下是一个典型的服务端实现

    def check_msg(request):
        """
        长轮询的服务端接口,当消息有新的动态时返回
        """
        version = request.POST.get("v", '')
        current = request.POST.get("current", '')
        try:
            i = 0
            while True:
                time.sleep(1)
                try:
                    x = BusinessInstanceStepDetail.objects.get(current)
                    # 有更新
                    dic = model_to_dict(x)
                    dic["done_time"] = str(dic["done_time"])
                    return render_json({'result': True, 'reload': False, "msg": u"数据已更新", "dict": dic})
                # 无更新
                except ObjectDoesNotExist:
                    pass
                if i == 3600:
                    return render_json({'result': False, 'reload': False, "msg": u""})
                i += 1
        except Exception, e:
            logger.error(u"获取新的动态失败:%s" % e)
        return render_json({'result': False, 'reload': False, "msg": u""})
    

    从该例子中可以看到:

    • 如果探测到更新,或者3600s都没更新,返回
    • 长轮询是将原本client侧做的轮询推到了server侧做。让server自己去轮询,轮询到消息更新后,再返回(通知client)。轮询动作本身始终是跑不掉的

    换句话说,长轮询对外暴露的是回调式的即时通知,实际底层还是standard polling。但是,在服务端侧的standard polling比客户端通过网络做的远程standard polling好多了

    应用

    长轮询一般应用与WebIM、ChatRoom和一些需要及时交互的网站应用中
    比如,应用程序 watch 配置服务器上的配置变更实现配置热更新,就可以使用long polling

    相关文章

      网友评论

          本文标题:long polling 2023-02-23

          本文链接:https://www.haomeiwen.com/subject/fagakdtx.html