Python 套接字服务器 - 踢功能

Python Socket Server - Kick Function

我试图将客户端从服务器中踢出,之后我得到以下异常:

Exception in thread Thread-2 (__handle_client):
Traceback (most recent call last):
  File "/Users/macbook/Desktop/Python Projects/Cars/Server/server.py", line 36, in __handle_client
    message = client.recv(1024).decode(FORMAT) 
OSError: [Errno 9] Bad file descriptor

在处理上述异常的过程中,又发生了一个异常:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 1009, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 946, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/macbook/Desktop/Python Projects/Cars/Server/server.py", line 41, in __handle_client
    client.send('You left the chat room'.encode(FORMAT)) 
OSError: [Errno 9] Bad file descriptor.

但是当我使用退出功能时它运行良好。两者都使用 __close_connection 函数。

这是我的代码:

def __handle_client(self,client):
    while True:
        try:
            message = client.recv(1024).decode(FORMAT) 
            if self.__handle_messsage(message,client) == True:
                break
        except:
            client.send('You left the chat room'.encode(FORMAT))
            self.__broadcast(f'{self.__clientnick[client]} has left the chat room!',)
            del self.__clientnick[client]
            client.close()
            break

    def __handle_messsage(self,message,client): 
    if  message == '/exit':
        exit_message = 'You have discinnected successfully.'
        self.__close_connction(exit_message,client)
        return True

    if message.startswith('/kick'):
        if self.__clientnick.get(client) == 'admin':
            for check_client in self.__clientnick: 
                if self.__clientnick.get(check_client) == message[6:len(message)]:
                    kick_message = 'You have been kicket from the chat room.'
                    self.__close_connction(kick_message,check_client)
                    return True
        else:
            client.send('You are not admin!'.encode(FORMAT))

    def __close_connection(self,message,client):
       client.send(message.encode(FORMAT))
       self.__broadcast(f'{self.__clientnick[client]} has left the chat room!',client)
       del self.__clientnick[client]
       client.close()

看起来你在踢的时候已经关闭了连接,这就是你得到异常的原因。第二个例外是当您尝试向已关闭的连接发送消息时。