Python http request.exceptions.ConnectionError :(“连接已中止。”,RemoteDisconnected(“远端封闭的无响应的连接”))

时间:2020-11-03 08:04:28

标签: python http python-requests long-polling

我正在编写聊天程序。我的每个客户在一个单独的线程(和另一个用于发布其自己的消息的线程)中都有一个向服务器开放获取请求。我不想有很多开销。也就是说,客户端不会频繁发送获取请求以查看是否存在任何看不见的消息。取而代之的是,它们始终只有一个打开的get请求来获取新消息,并且服务器一旦用新的看不见的消息对它们进行响应,便立即向服务器发送另一个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消息。

1 个答案:

答案 0 :(得分:1)

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