Pithikos / python-websocket-server

A simple fully working websocket-server in Python with no external dependencies
MIT License
1.13k stars 380 forks source link

_terminate_client_handlers does not close all clients #116

Open vzarutskiy opened 1 year ago

vzarutskiy commented 1 year ago

_terminate_client_handlers uses "for" cycle for clients disconnecting:

for client in self.clients:
            self._terminate_client_handler(client["handler"])

It executes _clientleft as finish(), there client is removed form self.clients list. It leads to an index shift and second client in list will be not disconnected. For example:

 def stop_server(self):
        print("before disconnect")
        print(self.server.clients)
        self.server.disconnect_clients_abruptly()
        print(self.server.clients)
        print("after disconnect")

Result: before disconnect

[{'id': 1, 'handler': <__main__.WSWithBinary object at 0x7ff85472c370>, 'address': ('192.168.23.143', 54582)}, {'id': 2, 'handler': <__main__.WSWithBinary object at 0x7ff8547f0a60>, 'address': ('192.168.23.143', 54584)}]
Client(1) disconnected
[{'id': 2, 'handler': <__main__.WSWithBinary object at 0x7ff8547f0a60>, 'address': ('192.168.23.143', 54584)}]
after disconnect

Possible fix:

    def _terminate_client_handlers(self):
        clients_list = self.clients.copy()
        for client in clients_list:
            self._terminate_client_handler(client["handler"])