import socket
import struct
import threading
import time


class A:
    def __init__(self, port, protocol='TCP', host="0.0.0.0"):
        self.host = host
        self.port = port
        self.protocol = protocol.upper()
        self.clients_handle = {}
        self.running = False
        self.accept_connections_thread = None

        if self.protocol in ['TCP', 'UDP']:
            self.socket = socket.socket(socket.AF_INET,
                                        socket.SOCK_STREAM if self.protocol == 'TCP' else socket.SOCK_DGRAM)
            self.socket.bind((self.host, self.port))
        if self.protocol == "MULTICAST":
            # 多播套接字
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)

            # 设置 SO_REUSEADDR 选项,以便在重新绑定时不报错
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

            # 加入多播组
            # group = self.socket.inet_aton( host )
            self.socket.setsockopt(
                socket.IPPROTO_IP,
                socket.IP_ADD_MEMBERSHIP,
                struct.pack(
                    '4sL',
                    socket.inet_aton(host),
                    socket.INADDR_ANY
                )
            )
            self.socket.bind(('0.0.0.0', port))

    def start_listen(self):

        self.running = True
        if 'TCP' == self.protocol:
            self.socket.listen(5)
            print(f"TCP Server started on {self.host or '0.0.0.0'}:{self.port}")
            self.accept_connections_thread = threading.Thread(target=self.accept_connections)  # 启动监听线程,监听线程
            self.accept_connections_thread.start()
        elif self.protocol in ["UDP", "MULTICAST"]:
            print(f"UDP Server started on {self.host or '0.0.0.0'}:{self.port}")
            self.accept_connections_thread = threading.Thread(target=self.accept_connections)  # 启动监听线程,监听线程
            self.accept_connections_thread.start()
        else:
            pass

        return True

    def accept_connections(self):
        if 'TCP' == self.protocol:
            while self.running:
                try:
                    print("正在监听要建立连接的设备")
                    client_socket, address = self.socket.accept()
                except:
                    continue
                self.clients_handle[client_socket.getpeername()] = client_socket
                print(f"New connection from {address}")
                client_socket.send(b"Welcome to the server!")
                threading.Thread(target=self.receive_data, args=(client_socket,)).start()
        else:
            self.receive_data()

    def receive_data(self, client_socket=None):
        if self.protocol == 'TCP':
            try:
                peername = client_socket.getpeername()
            except OSError:
                print("空包异常")
                if not self.running:
                    return
            while self.running:
                try:
                    print("正在接收TCP数据中...")
                    data = client_socket.recv(1024)
                    if data:
                        print(f"Received data: {data.decode()}")
                    else:
                        if peername in self.clients_handle:
                            del self.clients_handle[peername]
                        client_socket.close()
                        print(f"Client disconnected.")
                except OSError:
                    if not self.running:
                        break
                except:
                    if peername in self.clients_handle:
                        del self.clients_handle[peername]
                    client_socket.close()
                    print(f"Error receiving data from client.")
                    break
                continue
        elif self.protocol in ['UDP', "MULTICAST"]:

            heartbeat_timeout = 10  # 超时10秒则默认断开
            self.socket.settimeout(heartbeat_timeout)
            while self.running:
                try:
                    print("正在接收UDP数据中")
                    data, handle = self.socket.recvfrom(1024)
                    print(f"接收到数据{data}")
                    if not self.running:
                        print("检测到退出")
                        break
                    if handle not in self.clients_handle:
                        self.clients_handle[handle] = {}
                        (address, port) = handle
                    self.clients_handle[handle] = time.time()
                    (peername, port) = handle

                except socket.timeout:
                    current_time = time.time()

                    if len(self.clients_handle.keys()) > 0:
                        clients_handle = list(self.clients_handle.keys())
                        for handle in clients_handle:
                            last_heartbeat = self.clients_handle[handle]
                            if current_time - last_heartbeat > heartbeat_timeout:
                                del self.clients_handle[handle]
                                print(f"客户端 {handle} 已断开连接")
                                (address, port) = handle
                except OSError:
                    if not self.running:
                        print("异常")
                        break
                except BaseException as ex:
                    print(f"{ex}")

    def stop_listen(self):
        self.running = False
        try:
            if 'TCP' == self.protocol:
                
                for handle in self.clients_handle:  # 关闭客户端的连接
                    try:
                        self.clients_handle[handle].shutdown(socket.SHUT_RDWR)
                        self.clients_handle[handle].close()
                    except:
                        pass
                # 发送一个虚拟连接以解阻塞 accept
                try:
                    temp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    temp_socket.connect((self.host, self.port))  # 连接自己，解除 accept 阻塞
                    temp_socket.close()
                except OSError:
                    pass
                
                self.accept_connections_thread.join()
                self.socket.close()
                print("已退出TCP连接")
            else:
                # 发送一个空包来解除 recvfrom 阻塞
                print(f"发送到的空包数据为{self.host}-{self.port}")
                self.socket.sendto(b'', (self.host, self.port))
                if self.clients_handle.__len__() > 0:
                    for addr, last_heartbeat in self.clients_handle.items():
                        if addr in self.clients_handle:
                            del self.clients_handle[addr]
                            print(f"主动断开客户端 {addr}")

                self.socket.close()
                if self.accept_connections_thread:
                    self.accept_connections_thread.join()
                
                print("已退出UDP连接")
            return True
        except Exception as ex:
            print(ex)
            return False


a = A(8000, protocol='UDP', host="224.2.2.3")
a.start_listen()
time.sleep(2)
print(a.stop_listen())
time.sleep(2)

在此代码中当我调用stop_listen进行关闭时无法及时的关闭对应的线程，只有当超时时间到了后才能进行线程关闭，现在请在不修改超时时间的情况下实现及时的关闭对应的UDP线程，请为我编写出对应的代码