ch21: simplified asyncio examples with modern API
This commit is contained in:
parent
06f18c3765
commit
3deed0af7b
@ -38,26 +38,19 @@ async def handle_queries(reader, writer): # <3>
|
|||||||
# END TCP_CHARFINDER_TOP
|
# END TCP_CHARFINDER_TOP
|
||||||
|
|
||||||
# BEGIN TCP_CHARFINDER_MAIN
|
# BEGIN TCP_CHARFINDER_MAIN
|
||||||
def main(address='127.0.0.1', port=2323): # <1>
|
|
||||||
|
async def main(address='127.0.0.1', port=2323):
|
||||||
port = int(port)
|
port = int(port)
|
||||||
loop = asyncio.get_event_loop()
|
server = await asyncio.start_server(
|
||||||
server_coro = asyncio.start_server(handle_queries, address, port,
|
handle_queries, address, port)
|
||||||
loop=loop) # <2>
|
|
||||||
server = loop.run_until_complete(server_coro) # <3>
|
|
||||||
|
|
||||||
host = server.sockets[0].getsockname() # <4>
|
addr = server.sockets[0].getsockname()
|
||||||
print('Serving on {}. Hit CTRL-C to stop.'.format(host)) # <5>
|
print(f'Serving on {addr}. Hit CTRL-C to stop.')
|
||||||
try:
|
|
||||||
loop.run_forever() # <6>
|
|
||||||
except KeyboardInterrupt: # CTRL+C pressed
|
|
||||||
pass
|
|
||||||
|
|
||||||
print('Server shutting down.')
|
async with server:
|
||||||
server.close() # <7>
|
await server.serve_forever()
|
||||||
loop.run_until_complete(server.wait_closed()) # <8>
|
|
||||||
loop.close() # <9>
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
main(*sys.argv[1:]) # <10>
|
asyncio.run(main(*sys.argv[1:])) # <10>
|
||||||
# END TCP_CHARFINDER_MAIN
|
# END TCP_CHARFINDER_MAIN
|
||||||
|
@ -17,14 +17,12 @@ async def countdown(label, delay):
|
|||||||
print(f'{dt:7.4f}s \t{tabs}{label} = {n}')
|
print(f'{dt:7.4f}s \t{tabs}{label} = {n}')
|
||||||
n -= 1
|
n -= 1
|
||||||
|
|
||||||
loop = asyncio.get_event_loop()
|
coros = [
|
||||||
tasks = [
|
countdown('A', .7),
|
||||||
loop.create_task(countdown('A', .7)),
|
countdown('B', 2),
|
||||||
loop.create_task(countdown('B', 2)),
|
countdown('C', .3),
|
||||||
loop.create_task(countdown('C', .3)),
|
countdown('D', 1),
|
||||||
loop.create_task(countdown('D', 1)),
|
|
||||||
]
|
]
|
||||||
t0 = time.perf_counter()
|
t0 = time.perf_counter()
|
||||||
loop.run_until_complete(asyncio.wait(tasks))
|
asyncio.run(asyncio.wait(coros))
|
||||||
loop.close()
|
|
||||||
print('━' * 50)
|
print('━' * 50)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user