2016-03-29 4 views
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コールに置き換えることです。

答えて

0

awaitasync 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) 
+0

'ensure_future'は実行をスケジュールするだけであることに注意してください。もしあなたがいつ/いつ(もしエラーがあっても)それが完了すると保証するものではありません。 – kwarunek