gpt4 book ai didi

Python HTTP 简单服务器持久连接

转载 作者:行者123 更新时间:2023-12-01 01:01:29 29 4
gpt4 key购买 nike

我正在尝试创建一个简单的 HTTP 服务器,它将接收 POST 消息并提供简单的响应。我将标准 HTTPServer 与 python 一起使用。客户端使用 session() 进行连接,该 session() 应该使用持久连接,但在每次 POST 之后,我在调试中看到下面的消息,表明连接正在断开。

信息:urllib3.connectionpool:重置断开的连接:

DEBUG:urllib3.connectionpool:"GET/HTTP/1.1"200 无

当我尝试使用 Apache 时,客户端工作正常,因此我相信问题出在我的简单服务器配置中。如何配置简单的 http 服务器以使用持久连接?<​​/p>

简单的服务器Python代码:

from http.server import HTTPServer, BaseHTTPRequestHandler
from io import BytesIO
import time
import datetime
import logging


class SimpleHTTPRequestHandler(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_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b'Hello, world!')

def do_POST(self):
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)

curr_time = datetime.datetime.now()
data = ('{"msgid":"0x0002", "timestamp": "'+ str(curr_time) +'", "message":"Test http response from Raspberry Pi HTTP server"}').encode()

self.send_response(200)
self.end_headers()
response = BytesIO()
#response.write(b'This is POST request. ')
#response.write(b'Received: ')
response.write(data)
self.wfile.write(response.getvalue())

print("Simple HTTP Server running...")
logging.basicConfig(level=logging.DEBUG)
httpd = HTTPServer(('', 8000), SimpleHTTPRequestHandler)
httpd.serve_forever()

客户端Python代码:

#!/usr/bin/env python

# Using same TCP connection for all HTTP requests

import os
import json
import time
import datetime
import logging
import requests
from requests.auth import HTTPBasicAuth

logging.basicConfig(level=logging.DEBUG)
start_time = time.time()

def get_data(limit):
session = requests.Session()
url = "http://localhost:8000"

for i in range(10):
curr_time = datetime.datetime.now()
data = '{"msgid":"0x0001", "timestamp": "'+ str(curr_time) +'", "message":"Test http message from Raspberry Pi"}'

print("Sending Data: " + data)

response = session.post(url.format(limit), data)
#response_dict = json.loads(response.text)
print("Received Data: " + response.text)

if __name__ == "__main__":
limit = 1
get_data(limit)
print("--- %s seconds ---" % (time.time() - start_time))

最佳答案

您实际上并未在 POST 处理程序中设置 Connection header 。为了使持久连接正常工作,您还需要在响应中设置 Content-Length header ,以便客户端知道在重用连接之前要读取 HTTP 正文的字节数。

尝试这个根据您的代码改编的 POST 处理程序:

   def do_POST(self):
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)

# Process the request here and generate the entire response
response_data = b'{"stuff": 1234}'

# Send the response
self.send_response(200)
self.send_header("Connection", "keep-alive")
self.send_header("Content-Length", str(len(response_data)))
self.end_headers()

# Write _exactly_ the number of bytes specified by the
# 'Content-Length' header
self.wfile.write(response_data)

关于Python HTTP 简单服务器持久连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55764440/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com