From 0a160356e470963bb3232a736fb90e494f1fe377 Mon Sep 17 00:00:00 2001 From: Samartha Date: Sat, 12 Sep 2026 18:43:36 +0530 Subject: [PATCH] Document graceful server shutdown --- docs/faq/server.rst | 19 +++++++++++++++++++ docs/project/changelog.rst | 3 +++ 2 files changed, 22 insertions(+) diff --git a/docs/faq/server.rst b/docs/faq/server.rst index 05beeb26..ca9b2fb4 100644 --- a/docs/faq/server.rst +++ b/docs/faq/server.rst @@ -311,6 +311,25 @@ Here's how to adapt the example just above: The server will exit after all clients disconnect. +With the :mod:`threading` implementation, call ``Server.shutdown`` with +``close_connections=False`` instead:: + + from websockets.sync.server import serve + import threading + + server = serve(handler, "localhost", 8765) + server_thread = threading.Thread(target=server.serve_forever) + server_thread.start() + try: + # Run the application until it's time to stop. + ... + finally: + server.shutdown(close_connections=False) + server_thread.join() + +The server will return from ``Server.shutdown`` after all clients +disconnect. + How do I implement a health check? ---------------------------------- diff --git a/docs/project/changelog.rst b/docs/project/changelog.rst index 738288e4..961379d7 100644 --- a/docs/project/changelog.rst +++ b/docs/project/changelog.rst @@ -43,6 +43,9 @@ Improvements * :func:`~asyncio.client.connect` now closes connections with close code 1011 (internal error) when exiting the context manager with an exception. +* The FAQ documents how to stop asyncio and threading servers while keeping + existing connections open. See `issue #1756 + `_. .. _17.1: