Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get my asyncio client to call a socket server and waiting for response

I am working with an asyncio.Protocol server where the purpose is for the client to call the server, but wait until the server has responded and data is returned before stopping the client loop.

Based on the asyncio doc Echo Client and Server here: https://docs.python.org/3/library/asyncio-protocol.html#protocol-example-tcp-echo-server-and-client , results of transport.write(...) are returned immediately when called.

Through experience, calling loop.run_until_complete(coroutine) fails with RuntimeError: Event loop is running.

Running asyncio.sleep(n) in the data_received() method of the server doesn't have any effect either.

yield from asyncio.sleep(n) and yield from asyncio.async(asyncio.sleep(n)) in data_received() both hang the server.

My question is, how do I get my client to wait for the server to write a response before giving back control?

like image 997
NuclearPeon Avatar asked Mar 18 '23 13:03

NuclearPeon


1 Answers

I guess to never use transport/protocol pair directly.

asyncio has Streams API for high-level programming.

Client code can look like:

@asyncio.coroutine
def communicate():
    reader, writer = yield from asyncio.open_connection(HOST, PORT)
    writer.write(b'data')
    yield from writer.drain()
    answer = yield from reader.read()
    # process answer, maybe send new data back to server and wait for answer again
    writer.close()
like image 159
Andrew Svetlov Avatar answered Apr 13 '23 20:04

Andrew Svetlov