【问题标题】:Python HTTP Server/Client: Remote end closed connection without response errorPython HTTP Server/Client:远程结束关闭连接,没有响应错误
【发布时间】:2018-06-14 18:49:53
【问题描述】:

我使用BaseHTTPRequestHandler 制作了简单的 HTTP 服务器。问题是,当我想使用来自客户端的请求发布一些数据时,我得到ConnectionError。我从requests lib 文档中做了简单的请求。同样有趣的是,HTTP 服务器将从客户端接收数据并将其打印到控制台。我不明白这怎么可能。

客户:

def post_data():
    """Client method"""
    json_data = {
        'sender': 'User',
        'receiver': 'MY_SERVER',
        'message': 'Hello server! Sending some data.'}
    data_headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    data_payload = json.dumps(json_data)

    try:
        post = requests.post('http://localhost:8080/post', data=data_payload,
                             headers=data_headers)
        print(post.status_code)
    except ConnectionError as e:
        print("CONNECTION ERROR: ")
        print(e)

HTTP 服务器:

def do_POST(self):
    """Server method"""
    self.send_response(200)
    print("Receiving new data ...")
    content_length = int(self.headers['Content-Length'])
    post_data = self.rfile.read(content_length)
    print(post_data)

服务器结果:

C:\Users\mypc\Projects\PythonFiles\httpserver>python server.py

Fri Jan  5 01:09:12 2018: HTTP Server started on port 8080.
127.0.0.1 - - [05/Jan/2018 01:09:21] "POST /post HTTP/1.1" 200 -
Receiving new data ...
b'{"sender": "User", "receiver": "MY_SERVER", "message": "Hello server! Sending some data."}'

客户结果:

C:\Users\mypc\Projects\PythonFiles\httpserver>python client.py
CONNECTION ERROR:
('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))

C:\Users\mypc\Projects\PythonFiles\httpserver>

没有异常块的错误:

Traceback (most recent call last):
  File "C:\Python36\lib\site-packages\urllib3\connectionpool.py", line 601, in urlopen
    chunked=chunked)
  File "C:\Python36\lib\site-packages\urllib3\connectionpool.py", line 387, in _make_request
    six.raise_from(e, None)
  File "<string>", line 2, in raise_from
  File "C:\Python36\lib\site-packages\urllib3\connectionpool.py", line 383, in _make_request
    httplib_response = conn.getresponse()
  File "C:\Python36\lib\http\client.py", line 1331, in getresponse
    response.begin()
  File "C:\Python36\lib\http\client.py", line 297, in begin
    version, status, reason = self._read_status()
  File "C:\Python36\lib\http\client.py", line 266, in _read_status
    raise RemoteDisconnected("Remote end closed connection without"
http.client.RemoteDisconnected: Remote end closed connection without response

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python36\lib\site-packages\requests\adapters.py", line 440, in send
    timeout=timeout
  File "C:\Python36\lib\site-packages\urllib3\connectionpool.py", line 639, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "C:\Python36\lib\site-packages\urllib3\util\retry.py", line 357, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "C:\Python36\lib\site-packages\urllib3\packages\six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:\Python36\lib\site-packages\urllib3\connectionpool.py", line 601, in urlopen
    chunked=chunked)
  File "C:\Python36\lib\site-packages\urllib3\connectionpool.py", line 387, in _make_request
    six.raise_from(e, None)
  File "<string>", line 2, in raise_from
  File "C:\Python36\lib\site-packages\urllib3\connectionpool.py", line 383, in _make_request
    httplib_response = conn.getresponse()
  File "C:\Python36\lib\http\client.py", line 1331, in getresponse
    response.begin()
  File "C:\Python36\lib\http\client.py", line 297, in begin
    version, status, reason = self._read_status()
  File "C:\Python36\lib\http\client.py", line 266, in _read_status
    raise RemoteDisconnected("Remote end closed connection without"
urllib3.exceptions.ProtocolError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "client.py", line 137, in <module>
    start_parser()
  File "client.py", line 101, in start_parser
    send_requests(args.get, args.post)
  File "client.py", line 51, in send_requests
    post_data()
  File "client.py", line 129, in post_data
    headers=data_headers)
  File "C:\Python36\lib\site-packages\requests\api.py", line 112, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "C:\Python36\lib\site-packages\requests\api.py", line 58, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Python36\lib\site-packages\requests\sessions.py", line 508, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Python36\lib\site-packages\requests\sessions.py", line 618, in send
    r = adapter.send(request, **kwargs)
  File "C:\Python36\lib\site-packages\requests\adapters.py", line 490, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))

【问题讨论】:

标签: python error-handling python-requests httpserver


【解决方案1】:

看起来服务器在没有发送完整响应的情况下提前终止了连接。我浏览了文档,我认为这是问题所在(已添加重点):

send_response(code, message=None) 

添加响应头到 标头缓冲区并记录接受的请求。 HTTP 响应行 写入内部缓冲区,后跟 Server 和 Date 标题。这两个标头的值是从 version_string() 和 date_time_string() 方法,分别。如果 服务器不打算使用 send_header() 方法,然后 send_response() 应该跟一个 end_headers() 调用。

在 3.3 版中更改:标头存储到内部缓冲区,并且 end_headers() 需要显式调用。

所以您可能只需将调用添加到end_headers。如果您正在阅读一个旧示例(在 Python 3.3 之前),则不需要这样做。

【讨论】:

  • 我找不到这个end_headers 方法
  • @isquared-KeepitReal 您可能使用的是旧版本的库。如果您遇到问题,我建议发布一个新问题,以便您可以包含您的代码和您看到的任何错误
  • 我重试了几次,突然就奏效了。如果这都是关于过早终止的连接,那将是有道理的。
  • 很好的答案,非常感谢!调用 end_headers 为我修复了它。
  • @AdamGross 你是怎么解决的?如果您能回答这个问题,将不胜感激stackoverflow.com/questions/66778586/…
【解决方案2】:

你可以像 Peter Gibson 所说的那样放置 end_headers

self.send_header('Content-Type', 'blabla' )

self.end_headers()

【讨论】:

    猜你喜欢
    • 2020-12-30
    • 2021-10-17
    • 2017-03-12
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2021-04-09
    相关资源
    最近更新 更多