-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasyncio_echo_client_coroutine.py
More file actions
53 lines (44 loc) · 1.25 KB
/
asyncio_echo_client_coroutine.py
File metadata and controls
53 lines (44 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import asyncio
import functools
import logging
import sys
MESSAGES = [
b"This is the message. ",
b"It will be sent ",
b"in parts.",
]
SERVER_ADDRESS = ("localhost", 10000)
logging.basicConfig(
level=logging.DEBUG,
format="%(name)s: %(message)s",
stream=sys.stderr,
)
log = logging.getLogger("main")
event_loop = asyncio.get_event_loop()
async def echo_client(address, messages):
log = logging.getLogger("echo_client")
log.debug("connecting to {} port {}".format(*address))
reader, writer = await asyncio.open_connection(*address)
# This could be writer.writelines() except that
# would make it harder to show each part of the message
# being sent.
for msg in messages:
writer.write(msg)
log.debug("sending {!r}".format(msg))
if writer.can_write_eof():
writer.write_eof()
await writer.drain()
log.debug("waiting for response")
while True:
data = await reader.read(128)
if data:
log.debug("received {!r}".format(data))
else:
log.debug("closing")
writer.close()
return
try:
event_loop.run_until_complete(echo_client(SERVER_ADDRESS, MESSAGES))
finally:
log.debug("closing event loop")
event_loop.close()