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'))

我正在写一个聊天程序。我的每个客户在一个单独的线程中都有一个对服务器的开放获取请求(另一个线程用于 posting 他们自己的消息)。我不想有很多开销。也就是说,客户端不会频繁发送 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 套接字编程中遇到过同样的问题,当我想使用套接字在两个函数中进行通信时,有时会遇到一些错误?但是,这里我只想在长轮询功能中进行通信,而不是在其他任何地方进行通信。

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

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

客户:

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

服务器:

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

客户端第一次输入时,他输入自己的名字,然后开始发送 GET/receive 请求。然后客户可以通过发送 POST/message 请求将他的消息发送给其他人。每当用户向服务器发送消息时,服务器都会找到他(通过他的授权)并更新所有其他客户端 unseenMessages 这样只要他们的长轮询线程继续,他们就会收到新消息和他们的客户端也立即发送另一条 GET/receive 消息。

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