【问题标题】:asyncio.sleep from within a UDP server not working [duplicate]UDP服务器中的asyncio.sleep不起作用[重复]
【发布时间】:2016-03-29 13:01:42
【问题描述】:

我正在使用asyncio UDP server example 并希望在datagram_received 方法中获得sleep

import asyncio

class EchoServerProtocol:
    def connection_made(self, transport):
        self.transport = transport

    def datagram_received(self, data, addr):
        message = data.decode()
        print('Received %r from %s' % (message, addr))
        # Sleep
        await asyncio.sleep(1)
        print('Send %r to %s' % (message, addr))
        self.transport.sendto(data, addr)

loop = asyncio.get_event_loop()
print("Starting UDP server")
# One protocol instance will be created to serve all client requests
listen = loop.create_datagram_endpoint(EchoServerProtocol,
                                       local_addr=('127.0.0.1', 9999))
transport, protocol = loop.run_until_complete(listen)

try:
    loop.run_forever()
except KeyboardInterrupt:
    pass

transport.close()
loop.close()

这会失败,并在睡眠行 (Python 3.5.1) 上显示 SyntaxError。使用time.sleep 显然不起作用,因为它会阻止接收任何其他数据报。有关如何解决此问题的任何提示?

我们的目标是用真正的非阻塞 I/O 调用替换这个 sleep

【问题讨论】:

    标签: python-3.x python-asyncio


    【解决方案1】:

    似乎await 必须生活在async def(协程)中。为此,您必须通过asyncio.ensure_future 拨打电话。

    def datagram_received(self, data, addr):
        asyncio.ensure_future(self.reply(data, addr))
    
    async def reply(self, data, addr):
        await asyncio.sleep(1)
        self.transport.sendto(data, addr)
    

    【讨论】:

    • 请记住,ensure_future 只安排执行。您无法保证何时/如何(有错误)完成。
    猜你喜欢
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 2010-11-12
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多