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

Getting an exeption when shutting down in threaded mode #104

Open RoccoMarco opened 1 year ago

RoccoMarco commented 1 year ago

Hi, I am getting an exception when I call shutdown_gracefully()

ERROR:websocket_server.websocket_server:**** Exception in child thread <WebsocketServerThread(Thread-162 (serve_forever), started daemon 25036)>: [WinError 10038] An operation was attempted on something that is not a socket


Looks like the issue is that the thread is still running when the websocket is closed and this triggers an operation of the closed socket

Any hint?

RoccoMarco commented 1 year ago

I think the solution is to reorder the shout down functions and as good measure add a join

    def _shutdown_gracefully(self, status=CLOSE_STATUS_NORMAL, reason=DEFAULT_CLOSE_REASON):
        """
        Send a CLOSE handshake to all connected clients before terminating server
        """
        self.keep_alive = False
        self._disconnect_clients_gracefully(status, reason)
        self.shutdown()
        self.thread.join()
        self.server_close()

    def _shutdown_abruptly(self):
        """
        Terminate server without sending a CLOSE handshake
        """
        self.keep_alive = False
        self._disconnect_clients_abruptly()
        self.shutdown()
        self.thread.join()
        self.server_close()
zpfz commented 1 year ago

I think the solution is to reorder the shout down functions and as good measure add a join

    def _shutdown_gracefully(self, status=CLOSE_STATUS_NORMAL, reason=DEFAULT_CLOSE_REASON):
        """
        Send a CLOSE handshake to all connected clients before terminating server
        """
        self.keep_alive = False
        self._disconnect_clients_gracefully(status, reason)
        self.shutdown()
        self.thread.join()
        self.server_close()

    def _shutdown_abruptly(self):
        """
        Terminate server without sending a CLOSE handshake
        """
        self.keep_alive = False
        self._disconnect_clients_abruptly()
        self.shutdown()
        self.thread.join()
        self.server_close()

Hi, bro~it seems to test failed. But my console output :

ERROR:websocket_server.websocket_server:Invalid file descriptor: -1

have u the best way to solve this issue?