资讯 小学 初中 高中 语言 会计职称 学历提升 法考 计算机考试 医护考试 建工考试 教育百科
栏目分类:
子分类:
返回
空麓网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
空麓网 > 计算机考试 > 面试经验 > 面试问答

与HTTP服务器的urllib.request连接的持久性

面试问答 更新时间: 发布时间: 计算机考试归档 最新发布

与HTTP服务器的urllib.request连接的持久性

urllib.request
不支持持久连接。
'Connection:close'
代码中有硬编码。但
http.client
部分支持持久连接(包括旧版http / 1.0
keep-alive
)。因此,问题标题可能会引起误解。


我想在我们的其中一台Web服务器上进行一些性能测试,以了解服务器如何处理大量持久连接。不幸的是,我对HTTP和Web测试不是很熟悉。

您可以使用现有的http测试工具(例如slowloris和httperf)来代替自己编写。


如何使这些连接保持活动状态?

要关闭http / 1.1连接,客户端应明确指定

Connection:close
标头,否则服务器会认为该连接是持久的(尽管它可能随时关闭它,直到它尝试读取/写入连接时才
http.client
知道该连接)。

conn.connect()
几乎立即返回,并且线程结束。要强制每个线程维护与服务器的http连接,您可以:

import timedef make_http_connection(*args, **kwargs):    while True: # make new http connections        h = http.client.HTTPConnection(*args, **kwargs)        while True: # make multiple requests using a single connection try:     h.request('GET', '/') # send request; make conn. on the first run     response = h.getresponse()     while True: # read response slooowly         b = response.read(1) # read 1 byte         if not b: break         time.sleep(60) # wait a minute before reading next byte         #note: the whole minute might pass before we notice that          #  the server has closed the connection already except Exception:     break # make new connection on any error

注意:如果服务器返回,

'Connection: close'
则每个连接只有一个请求。


(另外,一个无关紧要的问题是,比我的代码末尾的丑陋的True:block更好的等待键盘中断的程序吗?)

要等待所有线程完成或

KeyboardInterrupt
发生,您可以:

while threads:    try:        for t in threads[:]: # enumerate threads t.join(.1) # timeout 0.1 seconds if not t.is_alive():    threads.remove(t)    except KeyboardInterrupt:        break

或类似这样的东西:

while threading.active_count() > 1:    try:        main_thread = threading.current_thread()        for t in threading.enumerate(): # enumerate all alive threads if t is not main_thread:    t.join(.1)    except KeyboardInterrupt:        break

后者可能由于各种原因而无法工作,例如,如果存在虚拟线程,例如以C扩展名启动的线程而不使用

threading
模块。

parallel.futures.ThreadPoolExecutor提供了比

threading
模块更高的抽象级别,并且可以隐藏一些复杂性。

您可以在单个线程中同时打开多个连接,而不是使用每个连接模型的线程,例如,使用

requests.async
gevent
直接打开。



转载请注明:文章转载自 http://www.konglu.com/
本文地址:http://www.konglu.com/it/636946.html
免责声明:

我们致力于保护作者版权,注重分享,被刊用文章【与HTTP服务器的urllib.request连接的持久性】因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理,本文部分文字与图片资源来自于网络,转载此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请立即通知我们,情况属实,我们会第一时间予以删除,并同时向您表示歉意,谢谢!

我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2023 成都空麓科技有限公司

ICP备案号:蜀ICP备2023000828号-2