Skip to content

Conversation

@kovan
Copy link
Contributor

@kovan kovan commented Feb 8, 2026

Summary

Adds a focused HOWTO for building a TCP chat server with asyncio streams, as suggested by @ZeroIntensity in the review of #144594:

There are some things here that look useful for the docs, but I don't think they need to be put under an "asyncio tutorial" umbrella. Instead, let's just make a HOWTO page for a chat server, since that seems to be the primary focus of all the content here.

The guide progressively builds from an echo server to a full chat server:

  • Starting with an echo server — introduces the streams API (start_server, StreamReader/StreamWriter, write/drain, close/wait_closed)
  • Building the chat server — adds client tracking, broadcasting, and cleanup
  • Extending the chat server — idle timeouts with asyncio.timeout, plus exercises
  • Common pitfalls — forgetting to await, blocking the event loop, fire-and-forget tasks

No overlap with the existing Conceptual Overview — this is purely a practical, hands-on HOWTO.

Test plan

  • make -C Doc check passes
  • make -C Doc html passes (no warnings)
  • All cross-references resolve correctly

🤖 Generated with Claude Code


📚 Documentation preview 📚: https://cpython-previews--144604.org.readthedocs.build/

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@bedevere-app bedevere-app bot mentioned this pull request Feb 8, 2026
@bedevere-app bedevere-app bot added docs Documentation in the Doc dir skip news labels Feb 8, 2026
@github-project-automation github-project-automation bot moved this to Todo in Docs PRs Feb 8, 2026
@ZeroIntensity ZeroIntensity self-requested a review February 9, 2026 11:59
Comment on lines 266 to 267
Common pitfalls
===============
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This section isn't really about the chat server. These are just common asyncio traps that would fit better in the tutorial or the reference docs.

- Explain concepts (start_server, StreamReader/StreamWriter) before code
- Use asyncio.TaskGroup for concurrent broadcasting
- Use contextlib.suppress instead of bare except/pass
- Remove Python test client, keep only nc/telnet
- Properly explain asyncio.timeout before showing usage
- Move implementation notes to code comments
- Remove Exercises and Common pitfalls sections
- Reorder seealso links in asyncio.rst

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@kovan
Copy link
Contributor Author

kovan commented Feb 10, 2026

I have made the requested changes; please review again

@bedevere-app
Copy link

bedevere-app bot commented Feb 10, 2026

Thanks for making the requested changes!

: please review the changes made to this pull request.

- Move write/drain and close/wait_closed explanations above the echo
  server example
- Explain async with server, serve_forever, and asyncio.run
- Break chat server into subsections: client tracking, broadcasting,
  then the complete example
- Show broadcast function separately before the full listing

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@kovan
Copy link
Contributor Author

kovan commented Feb 10, 2026

I have made the requested changes; please review again

@bedevere-app
Copy link

bedevere-app bot commented Feb 10, 2026

Thanks for making the requested changes!

: please review the changes made to this pull request.

Comment on lines +111 to +112
one at a time. :func:`contextlib.suppress` silently handles any
:exc:`ConnectionError` from clients that have already disconnected::
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we need to explain contextlib.suppress -- that's not part of asyncio and should fall under the umbrella of "basic Python knowledge". If you want, we can add a comment in the example explaining what it does.

Bob: Hi Alice!
Hello Bob!
Each message you type is broadcast to all other connected users.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Each message you type is broadcast to all other connected users.
Each message you type is broadcasted to all other connected users.

Comment on lines +212 to +221
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::
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This section should go above the complete example, and then the timeout code should be in the full code.

Comment on lines +28 to +36
Before building the chat server, let's start with something simpler: an echo
server that sends back whatever a client sends.

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.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice if we provided a small example of this before diving into the full echo server. We should start with something small, and then slowly build on that as we introduce concepts to the user.

Comment on lines +38 to +49
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.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here -- let's introduce both these concepts with their own examples.

asyncio.run(main())

To test, run the server in one terminal and connect from another using ``nc``
(or ``telnet``):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this in parentheses?

Suggested change
(or ``telnet``):
or ``telnet``:

Comment on lines +100 to +104
We store each connected 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.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is introduced as a solution, but we didn't explain the problem. Why do we need to store writers? Why do we need to remove them?

@ZeroIntensity
Copy link
Member

FTR, you don't have to say "I have made the requested changes" unless someone actually requested changes. You can just re-request a review.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: Todo

Development

Successfully merging this pull request may close these issues.

2 participants