Debian Codegraph @

docs/source/tutorial/echo-client.py

raw
1 # echo-client.py
2
3 import sys
4 import trio
5
6 # 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 server
10 PORT = 12345
11
12
13 async def sender(client_stream):
14 print("sender: started!")
15 while True:
16 data = b"async can sometimes be confusing, but I believe in you!"
17 print(f"sender: sending {data!r}")
18 await client_stream.send_all(data)
19 await trio.sleep(1)
20
21
22 async def receiver(client_stream):
23 print("receiver: started!")
24 async for data in client_stream:
25 print(f"receiver: got data {data!r}")
26 print("receiver: connection closed")
27 sys.exit()
28
29
30 async def parent():
31 print(f"parent: connecting to 127.0.0.1:{PORT}")
32 client_stream = await trio.open_tcp_stream("127.0.0.1", PORT)
33 async with client_stream:
34 async with trio.open_nursery() as nursery:
35 print("parent: spawning sender...")
36 nursery.start_soon(sender, client_stream)
37
38 print("parent: spawning receiver...")
39 nursery.start_soon(receiver, client_stream)
40
41
42 trio.run(parent)