1
私はasyncio
UDP server exampleで遊んでおり、datagram_received
の方法からsleep
を取得したいと考えています。UDPサーバー内からasyncio.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
を使用すると、他のデータグラムの受信を妨げるので、明らかに機能しません。これを解決する方法のヒント?
この目標は、sleep
を実際のノンブロッキングI/Oコールに置き換えることです。
'ensure_future'は実行をスケジュールするだけであることに注意してください。もしあなたがいつ/いつ(もしエラーがあっても)それが完了すると保証するものではありません。 – kwarunek