python - Python http requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))
问题描述
我正在写一个聊天程序。我的每个客户在一个单独的线程(以及另一个用于发布他们自己的消息的线程)中都有一个对服务器的开放获取请求。我不想有很多开销。也就是说,客户端不会经常发送 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 服务器 多线程 Web 服务器
推荐阅读
- sql - 如何将时间戳插入postgreSQL数据库
- nvidia - Debian 大黄蜂问题
- eclipse - Javadoc 未正确配置
- vb.net - 在 VB.NET 中使用或不使用 LINQ 格式化 DataTable 中的数据
- html - 仅使用弹性功能创建特殊网格
- c# - 如何将iOS项目中的类引用到xamarin中的主项目
- mongodb - 如何使用 setPoolLimit 来管理连接?
- r - 使用 $ 运算符和过滤器时,Rshiny 输出函数会中断
- jquery - 如何使用 Fulltable 创建文本区域和日期选择器?
- javascript - 我如何使它只发送部分消息?不和谐.js