An asyncio example

Adam Bartoš drekin at
Fri Jul 3 12:28:32 CEST 2015


I'm experimenting with asyncio. I have composed the following code. There
is a server handler and a client handler. I didn't want to split the code
into two files so I just used a socketpair, inspired by example
. However, my code doesn't work – it blocks because both sides are trying
to read more data. But if I close the writer on one side (the commented
line), whole connection is closed. So

1) is there a way to close just one direction of the connection?
2) In the blocked situaction even KeyboardInterrupt doesn't break the loop,
is that desired behavior? And why?
3) Are there some other issues with my code with respect to “best
practices” how to write a code like this?

Here is the code:

import asyncio
import socket

async def server(reader, writer):
    print("starting server")

    request = (await
    print("got request {!r}".format(request))

    response = "RESPONSE"
    print("response sent")

async def client(reader, writer):
    print("starting client")

    request = "REQUEST"
    # writer.close()
    print("request sent")

    response = (await
    print("got response {!r}".format(response))

async def connect(loop):
    serversock, clientsock = socket.socketpair()
    reader, writer = await asyncio.open_connection(sock=serversock,
    server_coro = server(reader, writer)
    reader, writer = await asyncio.open_connection(sock=clientsock,
    client_coro = client(reader, writer)

    server_task = loop.create_task(server_coro)
    client_task = loop.create_task(client_coro)

    return client_task

loop = asyncio.get_event_loop()
task = loop.run_until_complete(connect(loop))

Thank you, Adam Bartoš
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list