python-websockets / websockets

Library for building WebSocket servers and clients in Python

Home Page:https://websockets.readthedocs.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Closing connection with sync module

felipebiaggi opened this issue · comments

Sorry if this is a naive question, but I'm having trouble to closing my server while there are open connections.

A snippet of my implementation.

import websockets.sync.server
from types import FrameType
from multiprocessing import Process
from signal import SIGTERM, signal, Signals
from websockets.sync.connection import Connection
from websockets.sync.server import WebSocketServer

HOST = "127.0.0.1"
PORT = 65432


def handler(connection: Connection) -> None:
    print(f"Connection open - Client ID: <{connection.id}>")

    try:
        for message in connection:
            print(f"Client message: <{message}>")
    except Exception as err:
        print(f"Genetic error: <{err}>.")

    print(f"Connection close - Client ID: <{connection.id}>.")


class DummyServer:
    def __init__(self) -> None:
        self._server = self.create_server()

    def create_server(self) -> WebSocketServer:
        return websockets.sync.server.serve(handler=handler, host=HOST, port=PORT)

    def run(self) -> None:
        print("Server Start.")
        self._server.serve_forever()
        print("Server Stop.")

    def shutdown(self) -> None:
        print("Starting shutdown.")
        self._server.shutdown()

server = DummyServer()


def signal_handler(signal: Signals, frame: FrameType) -> None:
    server.shutdown()


if __name__ == "__main__":
    signal(SIGTERM, handler=signal_handler)

    server_process = Process(target=server.run)

    server_process.start()
    server_process.join()

If all clients have previously disconnected, the process finish as expected and self._server.serve_forever() is released, otherwise, the process will be blocked as shown in the image below.

Terminal output.
image

What would be the best approach for this specific case? I haven't gone in depth into the debugging process but I believe the process is stuck waiting for more messages from the client.