Python多线程参数传递及Socket服务器ConnectionResetError问题排查
多线程HTTP服务器连接错误问题及解决
问题描述
我正在编写一个支持多客户端连接的服务器程序,为每个客户端创建独立线程,但运行时出现连接相关错误。
原服务端代码
from socket import* import threading server = socket(AF_INET,SOCK_STREAM) server.bind(('localhost',9000)) def handle_client(conn,addr): print(addr) while(True): info = conn.recv(5000).decode() if(len(info)>0): print(info[0]) data = "HTTP/1.1 200 OK\n" data += "Content-Type: text/html; charset=utf-8\n" data += "\n" data += "<html><body>Hello World</body></html>\n\n" conn.sendall(data.encode()) conn.shutdown(SHUT_WR) def start(): server.listen() print(f"Server is listening on {server}") while(True): conn,addr = server.accept()# 等待客户端连接,返回连接对象和客户端地址元组 thread = threading.Thread(target=handle_client,args=(conn,addr)) thread.start() start()
错误信息
Server is listening on <socket.socket fd=272, family=2, type=1, proto=0, laddr=('127.0.0.1', 9000)>('127.0.0.1', 50959) 0 Exception in thread Thread-1 (handle_client): Traceback (most recent call last): File "C:\Users\Arun\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\Arun\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "e:\Desktop\Django\Django_Basics\Django_Basics\WebSockets\WorldsSimplestServer.py", line 25, in handle_client info = conn.recv(5000).decode() ^^^^^^^^^^^^^^^ ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
解决方法及修正代码
通过添加循环终止条件,处理完客户端请求后结束线程循环,解决了连接被强制关闭的问题。修正后的代码如下:
from socket import* import threading server = socket(AF_INET,SOCK_STREAM) server.bind(('localhost',9000)) def handle_client(conn,addr): print(addr) connected = True while(connected): info = conn.recv(5000).decode() if(len(info)>0): print(info[0]) data = "HTTP/1.1 200 OK\n" data += "Content-Type: text/html; charset=utf-8\n" data += "\n" data += "<html><body>Hello World</body></html>\n\n" conn.sendall(data.encode()) conn.shutdown(SHUT_WR) connected = False def start(): server.listen() print(f"Server is listening on {server}") while(True): conn,addr = server.accept()# 等待客户端连接,返回连接对象和客户端地址元组 thread = threading.Thread(target=handle_client,args=(conn,addr))# 模仿Java的写法,毕竟大家都爱Java... thread.start() start()
非常感谢各位的帮助!
内容的提问来源于stack exchange,提问作者user18920992
相关产品推荐
相关产品推荐

