我正在使用 asyncio.Protocol
服务器,其目的是让客户端调用服务器,但 等待 直到服务器响应并在停止客户端循环之前返回数据。
基于 asyncio doc Echo Client and Server here: https://docs.python.org/3/library/asyncio-protocol.html#protocol-example-tcp-echo-server-and-client ,调用时会立即返回 transport.write(...) 的结果。
通过经验,调用loop.run_until_complete(coroutine)
失败,用RuntimeError: Event loop is running.
在服务器的 asyncio.sleep(n)
方法中运行 data_received()
也没有任何效果。yield from asyncio.sleep(n)
中的 yield from asyncio.async(asyncio.sleep(n))
和 data_received()
都会挂起服务器。
我的问题是,如何让我的客户端在交还控制权之前等待服务器写入响应?
最佳答案
我想永远不要直接使用传输/协议(protocol)对。
asyncio 具有用于高级编程的 Streams API。
客户端代码可能如下所示:
@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()
关于sockets - 如何让我的 asyncio 客户端调用套接字服务器并等待响应,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25691062/