An asyncio example

Adam Bartoš drekin at gmail.com
Fri Jul 3 06:28:32 EDT 2015


Hello,

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
https://docs.python.org/3/library/asyncio-stream.html#register-an-open-socket-to-wait-for-data-using-streams
. 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 reader.read()).decode()
    print("got request {!r}".format(request))

    response = "RESPONSE"
    writer.write(response.encode())
    print("response sent")

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

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

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

async def connect(loop):
    serversock, clientsock = socket.socketpair()
    reader, writer = await asyncio.open_connection(sock=serversock,
loop=loop)
    server_coro = server(reader, writer)
    reader, writer = await asyncio.open_connection(sock=clientsock,
loop=loop)
    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))
loop.run_until_complete(task)


Thank you, Adam Bartoš
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20150703/b9ade590/attachment.html>


More information about the Python-list mailing list