-
-
Notifications
You must be signed in to change notification settings - Fork 34.5k
gh-79012: Add asyncio chat server HOWTO #144604
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
61b700c
gh-79012: Add asyncio chat server HOWTO
kovan 3f5b5ae
gh-79012: Address review feedback on asyncio chat server HOWTO
kovan 3b2356d
gh-79012: Restructure HOWTO to explain concepts before code
kovan 5582825
gh-79012: Restructure HOWTO based on review feedback
kovan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev
Previous commit
gh-79012: Restructure HOWTO based on review feedback
- Introduce concepts incrementally with small examples before full code - Split echo server into subsections: accepting connections, running the server, reading and writing data - Explain the problem (why track clients?) before showing the solution - Move idle timeout section above the complete example and integrate timeout into the full chat server code - Move join broadcast inside try block for proper cleanup on error - Add note about duplicate client names (exercise for the reader) - Replace contextlib.suppress prose explanation with inline comment - Fix telnet parentheses, apply "broadcasted" wording Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Loading branch information
commit 55828255d1502626f6f2a6a0bb07b0055296e6d6
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -28,29 +28,56 @@ Starting with an echo server | |
| Before building the chat server, let's start with something simpler: an echo | ||
| server that sends back whatever a client sends. | ||
|
|
||
| Accepting connections | ||
| --------------------- | ||
|
|
||
| The core of any asyncio network server is :func:`asyncio.start_server`. You | ||
| give it a callback function, a host, and a port. When a client connects, | ||
| asyncio calls your callback with two arguments: a | ||
| :class:`~asyncio.StreamReader` for receiving data and a | ||
| :class:`~asyncio.StreamWriter` for sending data back. Each connection runs | ||
| as its own coroutine, so multiple clients are handled concurrently. | ||
|
|
||
| The :meth:`~asyncio.StreamWriter.write` method buffers data without sending | ||
| it immediately. Awaiting :meth:`~asyncio.StreamWriter.drain` flushes the | ||
| buffer and applies back-pressure if the client is slow to read. Similarly, | ||
| :meth:`~asyncio.StreamWriter.close` initiates shutdown, and awaiting | ||
| :meth:`~asyncio.StreamWriter.wait_closed` waits until the connection is | ||
| fully closed. | ||
|
|
||
| Using the server as an async context manager (``async with server``) ensures | ||
| it is properly cleaned up when done. Calling | ||
| :meth:`~asyncio.Server.serve_forever` keeps the server running until the | ||
| program is interrupted. Finally, :func:`asyncio.run` starts the event loop | ||
| and runs the top-level coroutine. | ||
|
|
||
| Here is a complete echo server:: | ||
| asyncio calls your callback with a :class:`~asyncio.StreamReader` for receiving | ||
| data and a :class:`~asyncio.StreamWriter` for sending it back. | ||
|
|
||
| import asyncio | ||
| Here is a minimal callback that accepts a connection, prints the client's | ||
| address, and immediately closes it. The :meth:`~asyncio.StreamWriter.close` | ||
| method initiates the connection shutdown, and awaiting | ||
| :meth:`~asyncio.StreamWriter.wait_closed` waits until it is fully closed:: | ||
|
|
||
| async def handle_client(reader, writer): | ||
| addr = writer.get_extra_info('peername') | ||
| print(f'New connection from {addr}') | ||
| writer.close() | ||
| await writer.wait_closed() | ||
|
|
||
| Running the server | ||
| ------------------ | ||
|
|
||
| To keep the server running and accepting connections, use | ||
| :meth:`~asyncio.Server.serve_forever` inside an ``async with`` block. | ||
| Using the server as an async context manager ensures it is properly cleaned up | ||
| when done, and :meth:`~asyncio.Server.serve_forever` keeps it running until the | ||
| program is interrupted. Finally, :func:`asyncio.run` starts the event loop and | ||
| runs the top-level coroutine:: | ||
|
|
||
| async def main(): | ||
| server = await asyncio.start_server( | ||
| handle_client, '127.0.0.1', 8888) | ||
| async with server: | ||
| await server.serve_forever() | ||
|
|
||
| asyncio.run(main()) | ||
|
|
||
| Reading and writing data | ||
| ------------------------ | ||
|
|
||
| To turn this into an echo server, the callback needs to read data from the | ||
| client and send it back. :meth:`~asyncio.StreamReader.readline` reads one line | ||
| at a time, returning an empty :class:`bytes` object when the client | ||
| disconnects. | ||
|
|
||
| :meth:`~asyncio.StreamWriter.write` buffers outgoing data without sending it | ||
| immediately. Awaiting :meth:`~asyncio.StreamWriter.drain` flushes the buffer | ||
| and applies back-pressure if the client is slow to read. | ||
|
|
||
| With these pieces, the echo callback becomes:: | ||
|
|
||
| async def handle_client(reader, writer): | ||
| addr = writer.get_extra_info('peername') | ||
|
|
@@ -67,19 +94,8 @@ Here is a complete echo server:: | |
| writer.close() | ||
| await writer.wait_closed() | ||
|
|
||
| async def main(): | ||
| server = await asyncio.start_server( | ||
| handle_client, '127.0.0.1', 8888) | ||
| addr = server.sockets[0].getsockname() | ||
| print(f'Serving on {addr}') | ||
|
|
||
| async with server: | ||
| await server.serve_forever() | ||
|
|
||
| asyncio.run(main()) | ||
|
|
||
| To test, run the server in one terminal and connect from another using ``nc`` | ||
| (or ``telnet``): | ||
| or ``telnet``: | ||
|
|
||
| .. code-block:: none | ||
|
|
||
|
|
@@ -91,43 +107,74 @@ To test, run the server in one terminal and connect from another using ``nc`` | |
| Building the chat server | ||
| ======================== | ||
|
|
||
| The chat server extends the echo server with two additions: tracking connected | ||
| clients and broadcasting messages to everyone. | ||
| The echo server handles each client independently --- it reads from one client | ||
| and writes back to the same client. A chat server, on the other hand, needs to | ||
| deliver each message to *every* connected client. This means the server must | ||
| keep track of who is connected so it can send messages to all of them. | ||
|
|
||
| Client tracking | ||
| --------------- | ||
| Tracking connected clients | ||
| -------------------------- | ||
|
|
||
| We store each connected client's name and :class:`~asyncio.StreamWriter` in a | ||
| We store each client's name and :class:`~asyncio.StreamWriter` in a | ||
| module-level dictionary. When a client connects, ``handle_client`` prompts for | ||
| a name and adds the writer to the dictionary. A ``finally`` block ensures the | ||
| client is always removed on disconnect, even if the connection drops | ||
| unexpectedly. | ||
| a name and adds the writer to the dictionary. A ``finally`` block ensures | ||
| the client is always removed on disconnect, even if the connection drops | ||
| unexpectedly:: | ||
|
|
||
| connected_clients: dict[str, asyncio.StreamWriter] = {} | ||
|
|
||
| async def handle_client(reader, writer): | ||
| writer.write(b'Enter your name: ') | ||
| await writer.drain() | ||
| name = (await reader.readline()).decode().strip() | ||
| connected_clients[name] = writer | ||
| try: | ||
| ... # message loop (shown below) | ||
| finally: | ||
| del connected_clients[name] | ||
| writer.close() | ||
| await writer.wait_closed() | ||
|
|
||
| Broadcasting messages | ||
| --------------------- | ||
|
|
||
| To send a message to all clients, we define a ``broadcast`` function. | ||
| :class:`asyncio.TaskGroup` sends to all recipients concurrently rather than | ||
| one at a time. :func:`contextlib.suppress` silently handles any | ||
| :exc:`ConnectionError` from clients that have already disconnected:: | ||
| one at a time:: | ||
|
|
||
| async def broadcast(message, *, sender=None): | ||
| """Send a message to all connected clients except the sender.""" | ||
| async def send(writer): | ||
| # Ignore clients that have already disconnected. | ||
| with contextlib.suppress(ConnectionError): | ||
| writer.write(message.encode()) | ||
| await writer.drain() | ||
|
|
||
| async with asyncio.TaskGroup() as tg: | ||
| # Iterate over a copy: clients may leave during the broadcast. | ||
| for name, writer in list(connected_clients.items()): | ||
| if name != sender: | ||
| tg.create_task(send(writer)) | ||
|
|
||
|
|
||
| .. _asyncio-chat-server-timeout: | ||
|
|
||
| Adding an idle timeout | ||
| ---------------------- | ||
|
|
||
| To disconnect clients who have been idle for too long, wrap the read call in | ||
| :func:`asyncio.timeout`. This async context manager takes a delay in seconds. | ||
| If the enclosed ``await`` does not complete within that time, the operation is | ||
| cancelled and :exc:`TimeoutError` is raised, freeing server resources when | ||
| clients connect but stop sending data:: | ||
|
|
||
| async with asyncio.timeout(300): # 5-minute timeout | ||
| data = await reader.readline() | ||
|
|
||
| The complete chat server | ||
| ------------------------ | ||
|
|
||
| Putting it all together:: | ||
| Putting it all together, here is the complete chat server with client tracking, | ||
| broadcasting, and an idle timeout:: | ||
|
|
||
| import asyncio | ||
| import contextlib | ||
|
|
@@ -137,12 +184,12 @@ Putting it all together:: | |
| async def broadcast(message, *, sender=None): | ||
| """Send a message to all connected clients except the sender.""" | ||
| async def send(writer): | ||
| # Ignore clients that have already disconnected. | ||
| with contextlib.suppress(ConnectionError): | ||
| writer.write(message.encode()) | ||
| await writer.drain() | ||
|
|
||
| async with asyncio.TaskGroup() as tg: | ||
| # Iterate over a copy: clients may leave during the broadcast. | ||
| for name, writer in list(connected_clients.items()): | ||
| if name != sender: | ||
| tg.create_task(send(writer)) | ||
|
|
@@ -161,11 +208,17 @@ Putting it all together:: | |
| name = data.decode().strip() | ||
| connected_clients[name] = writer | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You may mention that the code doesn't handle two clients with the same name properly, it's left as an exercice to the reader :-) |
||
| print(f'{name} ({addr}) has joined') | ||
| await broadcast(f'*** {name} has joined the chat ***\n', sender=name) | ||
|
|
||
| try: | ||
| await broadcast(f'*** {name} has joined the chat ***\n', sender=name) | ||
| while True: | ||
| data = await reader.readline() | ||
| try: | ||
| async with asyncio.timeout(300): # 5-minute timeout | ||
| data = await reader.readline() | ||
| except TimeoutError: | ||
| writer.write(b'Disconnected: idle timeout.\n') | ||
| await writer.drain() | ||
| break | ||
| if not data: | ||
| break | ||
| message = data.decode().strip() | ||
|
|
@@ -175,7 +228,6 @@ Putting it all together:: | |
| except ConnectionError: | ||
| pass | ||
| finally: | ||
| # Ensure cleanup even if the client disconnects unexpectedly. | ||
| del connected_clients[name] | ||
| print(f'{name} ({addr}) has left') | ||
| await broadcast(f'*** {name} has left the chat ***\n') | ||
|
|
@@ -193,8 +245,13 @@ Putting it all together:: | |
|
|
||
| asyncio.run(main()) | ||
|
|
||
| .. note:: | ||
|
|
||
| This server does not handle two clients choosing the same name. Adding | ||
| support for unique names is left as an exercise for the reader. | ||
|
|
||
| To test, start the server and connect from two or more terminals using ``nc`` | ||
| (or ``telnet``): | ||
| or ``telnet``: | ||
|
|
||
| .. code-block:: none | ||
|
|
||
|
|
@@ -204,37 +261,4 @@ To test, start the server and connect from two or more terminals using ``nc`` | |
| Bob: Hi Alice! | ||
| Hello Bob! | ||
|
|
||
| Each message you type is broadcast to all other connected users. | ||
|
|
||
|
|
||
| .. _asyncio-chat-server-timeout: | ||
|
|
||
| Adding an idle timeout | ||
| ====================== | ||
|
|
||
| To disconnect clients who have been idle for too long, wrap the read call in | ||
| :func:`asyncio.timeout`. This async context manager takes a duration in | ||
| seconds. If the enclosed ``await`` does not complete within that time, the | ||
| operation is cancelled and :exc:`TimeoutError` is raised. This frees server | ||
| resources when clients connect but stop sending data. | ||
|
|
||
| Replace the message loop in ``handle_client`` with:: | ||
|
|
||
| try: | ||
| while True: | ||
| try: | ||
| async with asyncio.timeout(300): # 5-minute timeout | ||
| data = await reader.readline() | ||
| except TimeoutError: | ||
| writer.write(b'Disconnected: idle timeout.\n') | ||
| await writer.drain() | ||
| break | ||
| if not data: | ||
| break | ||
| message = data.decode().strip() | ||
| if message: | ||
| await broadcast(f'{name}: {message}\n', sender=name) | ||
| except ConnectionError: | ||
| pass | ||
| finally: | ||
| # ... (cleanup as before) ... | ||
| Each message you type is broadcasted to all other connected users. | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.