我正在使用asyncio.Protocol
服务器,该服务器的目的是让客户端调用服务器,但是请等到服务器响应并返回数据后再停止客户端循环。
基于此处的asyncio doc Echo客户端和服务器: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()
双方挂断服务器。
我的问题是,如何让我的客户在退还控制权之前等待服务器写入响应?
我猜永远不要直接使用传输/协议对。
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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句