Reputation: 591
I am trying to build a tcp server using Tornado and Asyncio. In the documentation of Tornado they say that await
and async
should work as a replacement for tornado.gen.coroutine
decorator, but I have a problem starting this server. What I am doing wrong here?
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()
This is the error:
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'
Upvotes: 1
Views: 1981
Reputation: 190
Change Server(io_loop=IOLoop.current().asyncio_loop)
to Server(io_loop=IOLoop.current())
since Server awaits IOLoop, not the asyncio loop itself.
Upvotes: 3