【问题标题】:Tornado asyncio tcp server throws AttributeError: '_UnixSelectorEventLoop'Tornado asyncio tcp 服务器抛出 AttributeError: '_UnixSelectorEventLoop'
【发布时间】:2016-05-17 11:55:23
【问题描述】:

我正在尝试使用 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'

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 现在我有这个错误Traceback (most recent call last): File "/Users/user/tornadotcp/venv/lib/python3.5/site-packages/tornado/tcpserver.py", line 271, in _handle_connection self.io_loop.add_future(future, lambda f: f.result()) File "/Users/user/tornadotcp/venv/lib/python3.5/site-packages/tornado/ioloop.py", line 589, in add_future assert is_future(future) AssertionError /Users/user/tornadotcp/venv/lib/python3.5/site-packages/tornado/netutil.py:274: RuntimeWarning: coroutine 'Server.handle_stream' was never awaited callback(connection, address)
    • 好像和这个问题有关:stackoverflow.com/questions/35542864/…
    猜你喜欢
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    相关资源
    最近更新 更多