我正在尝试使用Python套接字库创建一个聊天室,而最后一个错误我无法弄清楚如何解决。
以下是服务器和客户端的代码。客户端类的所有显示和数据输入都是通过另一个脚本处理的,该脚本处理其他功能和GUI。该脚本仅用于服务器处理。
问题是当客户端断开连接,服务器出现错误并崩溃时。重新启动服务器的唯一方法是强制关闭命令行并再次找到脚本。这当然是一个相当严重的问题。
服务器上收到的错误:
Traceback (most recent call last):
File "C:\Users\jamie\AppData\Local\Programs\Python\Python36- 32\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Users\jamie\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\jamie\Documents\Programming\Python\wxPython\ChatRoom\chatroom.py", line 15, in handler
data = c.recv(1024)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
我的服务器的代码。我没有包括我的GUI和主脚本,因为错误仅来自服务器。
import socket
import threading
class Server:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connections = []
port = 9000
def __init__(self):
self.sock.bind(('0.0.0.0', self.port))
self.sock.listen(1)
def handler(self, c, a):
while True:
data = c.recv(1024)
for connection in self.connections:
connection.send(data)
if not data:
print(str(a[0]) + ':' + str(a[1]) + ' disconnected.')
self.connections.remove(c)
c.close()
break
def run(self):
while True:
c, a = self.sock.accept()
cThread = threading.Thread(target=self.handler, args=(c,a))
cThread.daemon = True
cThread.start()
self.connections.append(c)
print(str(a[0]) + ':' + str(a[1]) + ' connected.')
class Client:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def sendMsg(self, msg):
self.sock.send(bytes(msg, 'utf-8'))
def __init__(self, address, port, mw):
self.mw = mw
self.sock.connect((address, port))
rThread = threading.Thread(target=self.reciever)
rThread.daemon = True
rThread.start()
def reciever(self):
while True:
data = self.sock.recv(1024)
if not data:
break
self.mw.MessageRecieved(str(data, 'utf-8'))
我真的很固执,但是在处理套接字和网络时还很新,所以我可能犯了一个愚蠢的错误!