相关疑难解决方法(0)

在asyncio.Protocol.data_received中调用协同程序

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()
Run Code Online (Sandbox Code Playgroud)

与以下客户一起使用:

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()
Run Code Online (Sandbox Code Playgroud)

随着self.fast_sqrt被召唤,一切都按预期工作.

self.slow_sqrt,它不起作用.

它也不适用self.fast_sqrt@asyncio.coroutine装饰器data_received.

我觉得我在这里缺少一些基本的东西.

完整的代码在这里: …

python network-programming yield coroutine python-asyncio

12
推荐指数
1
解决办法
3587
查看次数