我在執行新的Python asyncio模塊的asyncio.Protocol.data_received
回調中執行異步程序時遇到問題。調用asyncio.Protocol.data_received中的協同程序
考慮以下服務:
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(視窗)
- 的Python 3.3.3 + asyncio-0.2.1(FreeBSD)
這兩個問題是一樣的:與slow_sqrt
,客戶端/服務器將掛起什麼都不做。