【问题标题】:Python http requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))Python http requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))
【发布时间】:2020-11-03 08:04:28
【问题描述】:

我正在编写一个聊天程序。我的每个客户在一个单独的线程(以及另一个用于发布他们自己的消息的线程)中都有一个对服务器的开放获取请求。我不想有很多开销。也就是说,客户端不会经常发送 get 请求来查看是否有任何未见过的消息。相反,它们总是有一个打开的获取请求来获取新消息,并且一旦服务器用新的看不见的消息响应它们,它们就会立即向服务器发送另一个获取请求以保持更新等等。 所以在客户端,我有这样的东西:

def coms():
   headers = {'data': myAut.strip()}
   resp = requests.get("http://localhost:8081/receive", headers=headers,timeout=1000000)
   print(resp.text)
   t = threading.Thread(target=coms, args=())
   t.start()

在服务器端,我有这样的事情:

def do_GET(self):

    if self.path == '/receive':
        auth=self.headers['data']
    
    #Using auth, find who has sent this message
        u=None
        for i in range(len(users)):
            print(users[i].aut,auth)
            if users[i].aut==auth:
                u=users[i]
                break


        t=threading.Thread(target=long_Poll,args=(u,self))
        t.start()

def long_Poll(client,con):

   while True:

       if len(client.unreadMessages) != 0:
           print("IM GONNA RESPOND")
           con.end_headers()
           con.wfile.write(bytes(client.unreadMessages, "utf8"))
           client.unreadMessages=[]
           break
   con.send_response(200)
   con.end_headers()

这背后的逻辑是服务器想要进行长轮询,也就是说,它将GET/receive 请求保持在另一个忙等待线程中打开。当任何客户端通过POST/message 向服务器发送消息时,它只会将此新消息添加到其他客户端unseenMessages,因此一旦它们的线程运行,它们就会退出while True: 循环,服务器会为它们提供新的消息。换句话说,我想保持客户的GET/receive 处于打开状态,并且只要我愿意就不会回复它。 这个过程可能需要很长时间。可能聊天室闲置,很长时间没有消息。 现在我遇到的问题是,一旦我的客户发送了它的第一条GET/receive 消息,它就会收到这个错误,即使我在GET/receive 请求中设置了这么多的超时值。

C:\Users\erfan\Desktop\web\client\venv\Scripts\python.exe C:\Users\erfan\Desktop\web\client\Client.py
Hossein
Welcome to chatroom Hossein ! Have a nice time !
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Users\erfan\Desktop\web\client\venv\lib\site-packages\urllib3\connectionpool.py", line 677, in urlopen
    chunked=chunked,
  File "C:\Users\erfan\Desktop\web\client\venv\lib\site-packages\urllib3\connectionpool.py", line 426, in _make_request
    six.raise_from(e, None)
  File "<string>", line 3, in raise_from
  File "C:\Users\erfan\Desktop\web\client\venv\lib\site-packages\urllib3\connectionpool.py", line 421, in _make_request
    httplib_response = conn.getresponse()
  File "C:\Users\erfan\AppData\Local\Programs\Python\Python37\lib\http\client.py", line 1321, in getresponse
    response.begin()
  File "C:\Users\erfan\AppData\Local\Programs\Python\Python37\lib\http\client.py", line 296, in begin
    version, status, reason = self._read_status()
  File "C:\Users\erfan\AppData\Local\Programs\Python\Python37\lib\http\client.py", line 265, 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:\Users\erfan\Desktop\web\client\venv\lib\site-packages\requests\adapters.py", line 449, in send
    timeout=timeout
  File "C:\Users\erfan\Desktop\web\client\venv\lib\site-packages\urllib3\connectionpool.py", line 727, in urlopen
    method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]
  File "C:\Users\erfan\Desktop\web\client\venv\lib\site-packages\urllib3\util\retry.py", line 410, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "C:\Users\erfan\Desktop\web\client\venv\lib\site-packages\urllib3\packages\six.py", line 734, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\erfan\Desktop\web\client\venv\lib\site-packages\urllib3\connectionpool.py", line 677, in urlopen
    chunked=chunked,
  File "C:\Users\erfan\Desktop\web\client\venv\lib\site-packages\urllib3\connectionpool.py", line 426, in _make_request
    six.raise_from(e, None)
  File "<string>", line 3, in raise_from
  File "C:\Users\erfan\Desktop\web\client\venv\lib\site-packages\urllib3\connectionpool.py", line 421, in _make_request
    httplib_response = conn.getresponse()
  File "C:\Users\erfan\AppData\Local\Programs\Python\Python37\lib\http\client.py", line 1321, in getresponse
    response.begin()
  File "C:\Users\erfan\AppData\Local\Programs\Python\Python37\lib\http\client.py", line 296, in begin
    version, status, reason = self._read_status()
  File "C:\Users\erfan\AppData\Local\Programs\Python\Python37\lib\http\client.py", line 265, 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 "C:\Users\erfan\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner
    self.run()
  File "C:\Users\erfan\AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\erfan\Desktop\web\client\Client.py", line 13, in coms
    resp = requests.get("http://localhost:8081/receive", headers=headers,timeout=1000000)
  File "C:\Users\erfan\Desktop\web\client\venv\lib\site-packages\requests\api.py", line 76, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Users\erfan\Desktop\web\client\venv\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\erfan\Desktop\web\client\venv\lib\site-packages\requests\sessions.py", line 530, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\erfan\Desktop\web\client\venv\lib\site-packages\requests\sessions.py", line 643, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\erfan\Desktop\web\client\venv\lib\site-packages\requests\adapters.py", line 498, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))

================================================ ============================== 更新:

奇怪的部分是每当我将GET/receive 模块编辑成这个时:

 def do_GET(self):
      while True:
         pass

一切正常。 但是当我这样做时:

def do_GET(self):
   t=threading.Thread(target=long_Poll,args=(self))
   t.start()

def long_Poll(con):

  client =None
  while True:
    pass

它给客户端同样的错误!

我的意思是问题是因为我将 self 对象传递给另一个函数来响应?也许它会中断连接?我记得在 Java 套接字编程中遇到过同样的问题,当我想使用套接字在两个函数中进行通信时,有时会遇到一些错误?但是,这里我只想在长轮询函数中进行通信,而不是在其他任何地方。

========================================

更新: 我还将我的服务器和客户端代码放在这里。为简洁起见,我在此处发布 paste.ubuntu 链接。

客户:

https://paste.ubuntu.com/p/qJmRjYy4Y9/

服务器:

https://paste.ubuntu.com/p/rVyHPs4Rjz/

客户第一次键入时,输入他的姓名,然后开始发送GET/receive 请求。然后,客户可以通过发送POST/message 请求将他的消息发送给其他人。每当用户向服务器发送消息时,服务器都会(通过他的身份验证)找到他并更新所有其他客户端 unseenMessages 以便每当他们的长轮询线程继续时,他们都会收到新消息并且他们的客户端也会发送立即发送另一条GET/receive 消息。

【问题讨论】:

    标签: python http python-requests long-polling


    【解决方案1】:

    我找到了答案。我试图拥有一个使用单线程语法的多线程服务器! 我遵循这个线程来拥有一个多线程 HTTP 服务器 Multithreaded web server in python

    【讨论】:

      猜你喜欢
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-02
      • 2023-01-10
      • 1970-01-01
      • 2020-12-04
      相关资源
      最近更新 更多