如何使用asyncio

时间:2016-07-25 08:26:41

标签: python python-3.x telnet python-asyncio

首先,我应该说我对asyncio或其范式完全陌生。

所以我正在尝试使用asyncio.open_connection()实现asyncio(python 3.4)客户端,能够在tcp套接字(telnet)上发送请求并读取它的响应并听取其他方可能同时发送的内容。

换句话说,我需要我正在初始化的双向通信,因此我是客户。然而,到目前为止我使用StreamReaderStreamWriter找到的所有示例都被迫在读取空行后中断循环。此外,我需要以某种方式处理如果传入消息(每条消息正好是一行)是对前一个请求或另一方的原始消息的响应。 我觉得这样的事情可能有用。

class MyHandler:
    @asyncio.coroutine
    def connect(self):
        self.reader, self.writer = asyncio.open_connection('localhost', 2020)

        while True:
            msg = self.reader.readline()
            if msg is None:
                asyncio.sleep(1)
                continue
            self.handle_msg(msg)

    @asyncio.coroutine
    def request(self, msg):
        self.writer.write(msg)
        return self.reader.readline()

if __name__ == '__main__':
    h = MyHandler()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(h.connect)
    loop.close()

我在创建此问题时才编写此代码。现在我开始运行它,甚至在达到主要点之前就失败了。某种方式loop.run_until_complete(h.connect)TypeError: A Future or coroutine is required

失败

1 个答案:

答案 0 :(得分:1)

h.connect是一个函数,而h.connect()是一个协程。这意味着正确的代码是:

class MyHandler:
    @asyncio.coroutine
    def connect(self):
        self.reader, self.writer = asyncio.open_connection('localhost', 2020)

        while True:
            msg = yield from self.reader.readline()  # Yield from since it's a coroutine
            if msg.strip() is None:
                yield from asyncio.sleep(1)  # Also a coroutine
                continue
            self.handle_msg(msg)

    @asyncio.coroutine
    def request(self, msg):
        self.writer.write(msg)
        return (yield from self.reader.readline()) 

if __name__ == '__main__':
    h = MyHandler()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(h.connect())
    loop.close()