Tornado asyncio tcp服务器抛出AttributeError:' _UnixSelectorEventLoop'

时间:2016-05-17 11:55:23

标签: python-3.x tcp tornado python-asyncio

我正在尝试使用Tornado和Asyncio构建一个tcp服务器。在Tornado的documentation中,他们说awaitasync应该可以替代tornado.gen.coroutine装饰器,但我在启动此服务器时遇到问题。我在这里做错了什么?

from tornado.ioloop import IOLoop
from tornado.tcpserver import TCPServer
from tornado.iostream import StreamClosedError
from tornado.platform.asyncio import to_asyncio_future

class Server(TCPServer):

    async def handle_stream(self, stream, address):
        """Called when new IOStream object is ready for usage"""
        print('Incoming connection from %r', address)
        while True:
            try:
                message = await to_asyncio_future(stream.read_until('\n'.encode('utf8')))
                print("Message: ", message)
            except StreamClosedError:
                print("Good bye!!")
                break


if __name__ == "__main__":
    IOLoop.configure('tornado.platform.asyncio.AsyncIOLoop')
    server = Server(io_loop=IOLoop.current().asyncio_loop)
    server.listen(7000)
    IOLoop.current().start()

这是错误:

Traceback (most recent call last):
  File "tornadoasyncioserver.py", line 41, in <module>
    server.listen(7000)
  File "/Users/user/tornadotcp/venv/lib/python3.5/site-packages/tornado/tcpserver.py", line 127, in listen
    self.add_sockets(sockets)
  File "/Users/user/tornadotcp/venv/lib/python3.5/site-packages/tornado/tcpserver.py", line 144, in add_sockets
    io_loop=self.io_loop)
  File "/Users/user/tornadotcp/venv/lib/python3.5/site-packages/tornado/netutil.py", line 275, in add_accept_handler
    io_loop.add_handler(sock, accept_handler, IOLoop.READ)
AttributeError: '_UnixSelectorEventLoop' object has no attribute 'add_handler'

1 个答案:

答案 0 :(得分:1)

Server(io_loop=IOLoop.current().asyncio_loop)更改为Server(io_loop=IOLoop.current()),因为服务器等待IOLoop,而不是asyncio循环本身。