Python HTTP 服务器保持连接
Python HTTP server keep connection alive
我正在尝试测试用 C 编写的 HTTP 客户端,它向我计算机上的本地服务器发送 HTTP POST 请求。我在我的 POST 请求中添加了 headers 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')
我在客户端看到的header响应是:
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 连接参数?
默认情况下,BaseHTTPRequestHandler
发出 HTTP/1.0 响应,如您在 HTTP/1.0 200 OK
中所见。 HTTP/1.1
是 keep alive 响应所必需的,如 the doc (or for v3):
所示
protocol_version
This specifies the HTTP protocol version used in responses. If set to 'HTTP/1.1', the server will permit HTTP persistent connections;
however, your server must then include an accurate Content-Length
header (using send_header()) in all of its responses to clients. For
backwards compatibility, the setting defaults to 'HTTP/1.0'.
然后正如您在引用中看到的那样,您还必须为您的回复设置正确的 Content-Length。
请注意,目前您发送的回复没有 body,您应该为此使用 204(无内容)代码并添加 Content-length: 0
header,或添加一个小的 body(Content-Length 中的字节数正确,警告,这不是字符计数器,而是字节计数器,在 ascii7 中几乎相同,但与其他编码不同)。
我正在尝试测试用 C 编写的 HTTP 客户端,它向我计算机上的本地服务器发送 HTTP POST 请求。我在我的 POST 请求中添加了 headers 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')
我在客户端看到的header响应是:
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 连接参数?
默认情况下,BaseHTTPRequestHandler
发出 HTTP/1.0 响应,如您在 HTTP/1.0 200 OK
中所见。 HTTP/1.1
是 keep alive 响应所必需的,如 the doc (or for v3):
protocol_version
This specifies the HTTP protocol version used in responses. If set to 'HTTP/1.1', the server will permit HTTP persistent connections; however, your server must then include an accurate Content-Length header (using send_header()) in all of its responses to clients. For backwards compatibility, the setting defaults to 'HTTP/1.0'.
然后正如您在引用中看到的那样,您还必须为您的回复设置正确的 Content-Length。
请注意,目前您发送的回复没有 body,您应该为此使用 204(无内容)代码并添加 Content-length: 0
header,或添加一个小的 body(Content-Length 中的字节数正确,警告,这不是字符计数器,而是字节计数器,在 ascii7 中几乎相同,但与其他编码不同)。