asyncio.Protocol.data_received
新しい Python asyncioモジュールのコールバックで非同期処理を行う際に問題が発生しています。
次のサーバーを検討してください。
class MathServer(asyncio.Protocol):
@asyncio.coroutine
def slow_sqrt(self, x):
yield from asyncio.sleep(1)
return math.sqrt(x)
def fast_sqrt(self, x):
return math.sqrt(x)
def connection_made(self, transport):
self.transport = transport
#@asyncio.coroutine
def data_received(self, data):
print('data received: {}'.format(data.decode()))
x = json.loads(data.decode())
#res = self.fast_sqrt(x)
res = yield from self.slow_sqrt(x)
self.transport.write(json.dumps(res).encode('utf8'))
self.transport.close()
次のクライアントで使用:
class MathClient(asyncio.Protocol):
def connection_made(self, transport):
transport.write(json.dumps(2.).encode('utf8'))
def data_received(self, data):
print('data received: {}'.format(data.decode()))
def connection_lost(self, exc):
asyncio.get_event_loop().stop()
self.fast_sqrt
呼び出されると、すべてが期待どおりに機能します。
ではself.slow_sqrt
、動作しません。
また、self.fast_sqrt
および の@asyncio.coroutine
デコレータでは機能しませんdata_received
。
ここで根本的な何かが欠けているように感じます。
完全なコードは次のとおりです。
テスト済み:
- Python 3.4.0b1 (Windows)
- Python 3.3.3 + asyncio-0.2.1 (FreeBSD)
問題は両方で同じです。 をslow_sqrt
使用すると、クライアント/サーバーは何もせずにハングします。