我正在尝试测试一个用C编写的HTTP客户机,它向我的计算机上的本地服务器发送一个HTTP请求。我在POST请求中添加了类似于运行在我的计算机上的keep-alive服务器上的python3头:
<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我最终还是会得到一个断开连接回调,所以我的问题是如何从服务器端设置保持活动的连接参数?
发布于 2018-05-02 07:40:40
默认情况下,BaseHTTPRequestHandler会发出HTTP/1.0响应,就像您在HTTP/1.0 200 OK中看到的那样。HTTP/1.1是保持活动响应所必需的,如医生 (或对于v3)中所示:
protocol_version 这指定响应中使用的HTTP协议版本。如果设置为‘HTTP1.1’,服务器将允许HTTP持久连接;但是,您的服务器必须在其对客户端的所有响应中包含一个准确的内容长度标头(使用send_header())。为了向后兼容,设置默认为'HTTP/1.0‘。
然后,正如您在引号中所看到的,您还必须为您的响应设置正确的内容长度。
请注意,当前您发送的响应没有正文,应该使用204 (无内容)代码,并为此添加Content-length: 0头,或者添加一个小体(内容长度和警告中有正确的字节计数,这不是字符计数器,这是字节计数器,在ascii7中几乎相同,但与其他编码不同)。
https://stackoverflow.com/questions/50120102
复制相似问题