python-3.x - UDP 服务器内的 asyncio.sleep 不起作用

标签 python-3.x python-asyncio

我正在玩 asyncio UDP server example并希望有一个sleep来自datagram_received内方法。

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()

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

目标是取代这个 sleep具有真正的非阻塞 I/O 调用。

最佳答案

似乎 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)

关于python-3.x - UDP 服务器内的 asyncio.sleep 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36285065/

相关文章:

python - 用asyncio转换一个简单的多线程程序

python-3.x - hits>total - 限制为 10000 条记录 - 增加限制

python - 使用新类型重新抛出 Python 异常

python-asyncio - python3.5中没有提供asyncio.timeout?

从 loop.create_task() 引发的 python asyncio 异常

python - 为什么我的异步函数没有并行运行?

python asyncio,如何从另一个线程创建和取消任务

python - 如何将 JSON 中的推文保存到 Python 3.4 中的 txt 文件?

python - 在 Python 中使用函数列出文件夹名称

python - 指向python中指针的指针