4

我正在使用asyncio.Protocol服务器,其目的是让客户端调用服务器,但要等到服务器响应并返回数据,然后再停止客户端循环。

基于此处的 asyncio doc Echo Client and Server: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()两者中挂起服务器。

我的问题是,如何让我的客户在交还控制权之前等待服务器写响应?

4

2 回答 2

4

我想永远不要直接使用传输/协议对。

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()
于 2014-09-08T08:12:36.150 回答
3

您不必更改客户端代码。

回声客户端.py

#!/usr/bin/env python3.4
import asyncio

class EchoClient(asyncio.Protocol):
    message = 'Client Echo'

    def connection_made(self, transport):
        transport.write(self.message.encode())
        print('data sent: {}'.format(self.message))

    def data_received(self, data):
        print('data received: {}'.format(data.decode()))

    def connection_lost(self, exc):
        print('server closed the connection')
        asyncio.get_event_loop().stop()

loop = asyncio.get_event_loop()
coro = loop.create_connection(EchoClient, '127.0.0.1', 8888)
loop.run_until_complete(coro)
loop.run_forever()
loop.close()

诀窍是将您的代码(包括 self.transport 方法)放入协程并使用该wait_for()方法,将yield from语句放在需要返回值的语句之前,或者需要一段时间才能完成的语句:

回声服务器.py

#!/usr/bin/env python3.4
import asyncio

class EchoServer(asyncio.Protocol):
    def connection_made(self, transport):
        peername = transport.get_extra_info('peername')
        print('connection from {}'.format(peername))
        self.transport = transport

    def data_received(self, data):
        print('data received: {}'.format(data.decode()))
        fut = asyncio.async(self.sleeper())
        result = asyncio.wait_for(fut, 60)

    @asyncio.coroutine
    def sleeper(self):
        yield from asyncio.sleep(2)
        self.transport.write("Hello World".encode())
        self.transport.close()

loop = asyncio.get_event_loop()
coro = loop.create_server(EchoServer, '127.0.0.1', 8888)
server = loop.run_until_complete(coro)
print('serving on {}'.format(server.sockets[0].getsockname()))

try:
    loop.run_forever()
except KeyboardInterrupt:
    print("exit")
finally:
    server.close()
    loop.close()

调用echo-server.py然后echo-client.py,客户端将等待 2 秒,由 确定asyncio.sleep,然后停止。

于 2014-09-05T17:27:16.680 回答