Python HTTP服务器保持连接活跃

roo*_*kie 3 http httpserver http-headers python-3.x

我正在尝试测试用C编写的HTTP客户端,该客户端将HTTP POST请求发送到计算机上的本地服务器。我keep-alive在计算机上运行的python3 HTTP服务器上的POST请求中添加了标头,如下所示:

<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" 
}
Run Code Online (Sandbox Code Playgroud)

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')
Run Code Online (Sandbox Code Playgroud)

我在客户端看到的标头响应是:

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
Run Code Online (Sandbox Code Playgroud)

我仍然最终会得到断开连接回调,所以我的问题是如何从服务器端设置keep-alive连接参数?

reg*_*ero 5

BaseHTTPRequestHandler如您在中所见,默认情况下会发出HTTP / 1.0响应HTTP/1.0 200 OKHTTP/1.1保持响应是必需的,如doc(或v3)所示:

protocol_version

这指定了响应中使用的HTTP协议版本。如果设置为“ HTTP / 1.1”,则服务器将允许HTTP持久连接。但是,服务器在对客户端的所有响应中都必须包含准确的Content-Length标头(使用send_header())。为了向后兼容,该设置默认为“ HTTP / 1.0”。

然后,如您在报价中所见,您还必须为响应设置正确的Content-Length。

请注意,当前您发送的响应没有正文,您应该为此使用204(无内容)代码并添加Content-length: 0标头,或添加小正文(Content-Length中的字节数正确,警告,这不是字符计数器,这是一个字节计数器,在ascii7中几乎相同,但其他编码则不同)。