Python SimpleHTTPRequestHandler,如何保持 TCP 长连接

2016-11-27 23:03:38 +08:00
 axisray

这个是用来模拟测试环境的,但是 302 那个 response 的 FIN 被置 1 ,连接断开了 如何在以下过程中保持 TCP 长连接? GET->302->GET

from http.server import SimpleHTTPRequestHandler
from http.server import HTTPServer

#Listen Address
ADDR = ''
#Listen Port
PORT = 80

class WebRequestHandler(SimpleHTTPRequestHandler):
    def do_GET(self):
        #self.close_connection=False
        self.protocol_version='HTTP/1.1'
        rawpath =  self.path.split('?')[0]
        if(rawpath == '/ITPage/SurftheInternet.aspx' ):
            self.send_response(302)
            self.send_header('Content-Type','text/html; charset=utf-8')
            self.send_header('Location','/ITPage/SurftheInternet.html?openid=testestestestest')
            self.end_headers()
        if(rawpath == '/ITPage/SurftheInternet.html'):
            self.send_response(200)
            self.end_headers()
server = HTTPServer((ADDR,PORT),WebRequestHandler)
print("Server start!")
server.serve_forever()
5839 次点击
所在节点    Python
9 条回复
ryd994
2016-11-28 01:20:30 +08:00
1. protocol version 直接放 class 里
2. 设置 header Connection: keep-alive
qq446015875
2016-11-28 09:54:46 +08:00
@ryd994 我试了下,抓包确实看到了 302 没有 FIN ,但是浏览器似乎不认这个 302 ,浏览器 F12 没有记录到,也没有跳转
如果只按 1 操作,抓包没有 302 , python 没有回应 GET
qq446015875
2016-11-28 10:15:31 +08:00
我好像知道了, Content-Length 吧?
julyclyde
2016-11-28 11:01:00 +08:00
你自己写 handler 啊
那你输出的 header 里并没提到 Connection: Keep-Alive 啊
ryd994
2016-11-29 03:46:13 +08:00
@qq446015875 不是 content-length
你查查 Connection: keep-alive
axisray
2016-11-30 13:59:54 +08:00
@ryd994
不需要 Connection: Keep-Alive ,浏览器在发起 GET 请求的时候就已经包含了 Connection: Keep-Alive
而且 HTTP/1.1 默认就是长连接
我遇到的问题是因为没有包含 Content-Length
浏览器一直在等待数据,所以就卡死在哪了
添加 self.send_header('Content-Length','0')
这样就可以了
ryd994
2016-11-30 14:18:43 +08:00
说什么都比不上源码: https://hg.python.org/cpython/file/3.6/Lib/http/server.py#l344
你自己问的是连接断开了怎么办,怎么保持长连接
请求 header 和响应 header 是两回事
另外,你的问题文档里有明确说过: https://docs.python.org/3.7/library/http.server.html#http.server.BaseHTTPRequestHandler.protocol_version
qq446015875
2016-12-03 15:58:06 +08:00
@ryd994 嗯是我描述不清楚,我也是发完帖子注意到文档里说要加 content-length
还是谢谢你了:)
axisray
2016-12-03 16:06:34 +08:00
我擦,没注意,暴露马甲了....

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/323697

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX