long polling 2023-02-23

长轮询 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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,589评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,615评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,933评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,976评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,999评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,775评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,474评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,359评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,854评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,007评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,146评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,826评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,484评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,029评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,153评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,420评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,107评论 2 356

推荐阅读更多精彩内容