如何处理与 python 套接字的断开连接? (连接重置错误)

How do I handle a disconnect with python sockets? (ConnectionResetError)

我正在制作一个带有 python 套接字的简单服务器和客户端,我想知道如何处理断开连接。每当我的一个客户端断开连接时,它都会给出 ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host 并且服务器停止 运行。这是有道理的,但我该如何处理这样的断开连接呢?这是我的服务器代码:(我知道我的第一个套接字项目很乱)

import socket
import threading


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Connection oriented, IPV4

s.bind((socket.gethostname(), 1234))#Ip address information, port
s.listen(5)

connections = [] #Connection added to this list every time a client connects

def accptconnection():
    while True:
        clientsocket, address = s.accept()
        connections.append(clientsocket) #adds the clients information to the connections array
        threading.Thread(target=recvmsg, args=(clientsocket, address,)).start()

def recvmsg(clientsocket, address):
    while True:
        print(f"Connection from {address} has been established.")
        msg = clientsocket.recv(1024)
        if len(msg.decode('utf-8')) > 0:
            print(msg.decode("utf-8"))
        for connection in connections: #iterates through the connections array and sends message to each one
            msgbreak = msg
            connection.send(bytes(str(msgbreak.decode("utf-8")), "utf-8"))


accptconnection()

如有帮助,在此先感谢!

这应该可以防止服务器关闭,并清理出现连接错误的客户端:

import socket
import threading


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Connection oriented, IPV4

s.bind((socket.gethostname(), 1234))#Ip address information, port
s.listen(5)

connections = [] #Connection added to this list every time a client connects

def accptconnection():
    while True:
        clientsocket, address = s.accept()
        connections.append(clientsocket) #adds the clients information to the connections array
        threading.Thread(target=recvmsg, args=(clientsocket, address,)).start()

def recvmsg(clientsocket, address):
    print(f"Connection from {address} has been established.")
    while True:
        try:
            msg = clientsocket.recv(1024)
        except ConnectionError:
            print(f"Connection from {address} has been lost.")
            if clientsocket in connections:
                connections.remove(clientsocket)
            return
        if len(msg.decode('utf-8')) > 0:
            print(msg.decode("utf-8"))
        for connection in connections: #iterates through the connections array and sends message to each one
            msgbreak = msg
            try:
                connection.send(bytes(str(msgbreak.decode("utf-8")), "utf-8"))
            except ConnectionError:
                 print(f"Unable to reach client with socket {connection}")
                 if connection in connections:
                     connections.remove(connection)

accptconnection()