| 1 |
# echo-server.py |
| 2 |
|
| 3 |
import trio |
| 4 |
from itertools import count |
| 5 |
|
| 6 |
# Port is arbitrary, but: |
| 7 |
# - must be in between 1024 and 65535 |
| 8 |
# - can't be in use by some other program on your computer |
| 9 |
# - must match what we set in our echo client |
| 10 |
PORT = 12345 |
| 11 |
|
| 12 |
CONNECTION_COUNTER = count() |
| 13 |
|
| 14 |
|
| 15 |
async def echo_server(server_stream): |
| 16 |
# Assign each connection a unique number to make our debug prints easier |
| 17 |
# to understand when there are multiple simultaneous connections. |
| 18 |
ident = next(CONNECTION_COUNTER) |
| 19 |
print(f"echo_server {ident}: started") |
| 20 |
try: |
| 21 |
async for data in server_stream: |
| 22 |
print(f"echo_server {ident}: received data {data!r}") |
| 23 |
await server_stream.send_all(data) |
| 24 |
print(f"echo_server {ident}: connection closed") |
| 25 |
# FIXME: add discussion of (Base)ExceptionGroup to the tutorial, and use |
| 26 |
# exceptiongroup.catch() here. (Not important in this case, but important |
| 27 |
# if the server code uses nurseries internally.) |
| 28 |
except Exception as exc: |
| 29 |
# Unhandled exceptions will propagate into our parent and take |
| 30 |
# down the whole program. If the exception is KeyboardInterrupt, |
| 31 |
# that's what we want, but otherwise maybe not... |
| 32 |
print(f"echo_server {ident}: crashed: {exc!r}") |
| 33 |
|
| 34 |
|
| 35 |
async def main(): |
| 36 |
await trio.serve_tcp(echo_server, PORT) |
| 37 |
|
| 38 |
|
| 39 |
# We could also just write 'trio.run(trio.serve_tcp, echo_server, PORT)', but real |
| 40 |
# programs almost always end up doing other stuff too and then we'd have to go |
| 41 |
# back and factor it out into a separate function anyway. So it's simplest to |
| 42 |
# just make it a standalone function from the beginning. |
| 43 |
trio.run(main) |