from PyQt5.QtWebSockets import QWebSocketServer, QWebSocket
from PyQt5.QtNetwork import QHostAddress


class WebSocketServer:
    def __init__(self):
        self.server = QWebSocketServer("My Server", QWebSocketServer.SslMode.NonSecureMode)
        self.server.closed.connect(self.onServerClosed)
        self.server.newConnection.connect(self.onNewConnection)
        self.clients = []

    def start(self):
        # address = QHostAddress(QHostAddress.LocalHost)
        address = QHostAddress("127.0.0.1")
        port = 18080
        if self.server.listen(address, port):
            print("WebSocket server started at {}:{}".format(address.toString(), port))
        else:
            print("Failed to start WebSocket server")

    def stop(self):
        print("WebSocket server stoped")
        self.server.close()

    def sendToAllClients(self, message):
        num_clients = len(self.clients)
        print("已连接客户端数量：" + str(num_clients))
        for client in self.clients:
            client.sendTextMessage(message)

    def onServerClosed(self):
        print("WebSocket server closed")

    def onNewConnection(self):
        connection = self.server.nextPendingConnection()
        connection.disconnected.connect(lambda: self.onClientDisconnected(connection))
        self.clients.append(connection)
        print("New client connected")

    def onClientDisconnected(self, client):
        if client in self.clients:
            self.clients.remove(client)
        print("Client disconnected")
