본문 바로가기

[공부용]참고 사이트 모음/[python]

asyncio.sleep within asyncio UDP server

stackoverflow.com/questions/36285065/asyncio-sleep-from-within-a-udp-server-not-working

 

asyncio.sleep from within a UDP server not working

I'm playing with asyncio UDP server example and would like to have a sleep from within the datagram_received method. import asyncio class EchoServerProtocol: def connection_made(self, transpo...

stackoverflow.com

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)

It seems that the await has to live in an async def (coroutine). To do so, you must fire a call via asyncio.ensure_future.

Keep in mind that ensure_future only schedules the execution. You do not have guarantee when/how (with error) it will complete if ever.

 

asyncio 를 이용한 비동기 소켓 서버를 만들때 중간에 잠시 sleep하고 데이터를 보내야 할 때가 있을 것이다. 이때 time.sleep(delay)을 사용하면 거기서 블록이 되므로 asyncio.sleep(delay)를 사용하여야 하는데 그때 위와같이 사용하면 된다.