Python HTTP服务器保持连接活跃

7

我想测试一个用C语言编写的HTTP客户端,它向我的计算机上的本地服务器发送HTTP POST请求。我已经在我的POST请求中添加了keep-alive头部,它看起来像这样在我计算机上运行的Python3 HTTP服务器:

<ip-address-1> - - [29/Apr/2018 18:27:49] "POST /html HTTP/1.1" 200 -
Host: <ip-address-2>
Content-Type: application/json
Content-Length: 168
Connection: Keep-Alive
Keep-Alive: timeout=5, max=100


INFO:root:POST request,
Body:
{
"field": "abc",
"time": "2018-04-29T01:27:50.322000Z" 
}

HTTP服务器的POST处理程序如下所示:
class S(BaseHTTPRequestHandler):
    def _set_response(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.send_header("Connection", "keep-alive")
        self.send_header("keep-alive", "timeout=5, max=30")
        self.end_headers()

    def do_POST(self):
        content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
        post_data = self.rfile.read(content_length) # <--- Gets the data itself
        print(self.headers)
        logging.info("POST request,\nBody:\n%s\n", post_data.decode('utf-8'))

        self._set_response()
        self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))

def run(server_class=HTTPServer, handler_class=S, port=8080):
    logging.basicConfig(level=logging.INFO)
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    logging.info('Starting httpd...\n')
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    logging.info('Stopping httpd...\n')

客户端看到的头响应是:
HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.5.2
Date: Tue, 29 April 2018 16:07:42 GMT
Content-type: text/html
Connection: keep-alive
keep-alive: timeout=5, max=30

我最终还是收到了一个断开连接的回调,所以我的问题是如何从服务器端设置keep-alive连接参数?

1个回答

9
默认情况下,BaseHTTPRequestHandler 发出的是 HTTP/1.0 响应,如 HTTP/1.0 200 OK 所示。要使用保持活动连接响应,需要使用 HTTP/1.1,请参见 文档(或 v3):

protocol_version

此选项指定响应中使用的 HTTP 协议版本。如果设置为 'HTTP/1.1',则服务器将允许 HTTP 持久连接;但是,您的服务器必须在所有响应中(使用 send_header())包含准确的 Content-Length 标头以便与客户端进行通信。为了向后兼容,该设置默认为 'HTTP/1.0'。

然后,如引用中所示,您还需要为响应设置正确的 Content-Length。
请注意,目前您发送的响应没有正文,您应该使用204(无内容)代码,并添加Content-length: 0头部,或者添加一个小的正文(在Content-Length中正确计算字节数,警告,这不是字符计数器,而是字节计数器,在ascii7中几乎相同,但在其他编码中不同)。

1
保持连接似乎适用于默认的HTTP/1.0,至少对于回答GET请求而言。我还遇到了在TCP套接字上设置它本身的情况。 - MayeulC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接