Tornado read until close 方法错误
Tornado read until close method error
我正在尝试使用龙卷风在 python 中创建 TCP 服务器。 我的句柄流方法如下所示,
async def handle_stream(self, stream, address):
while True:
try:
stream.read_until_close(streaming_callback=self._on_read)
except StreamClosedError:
break
在 _on_read
方法中,我试图读取和处理数据,但每当新客户端连接到服务器时,它都会出现 AssertionError: Already reading
错误。
File "/.local/lib/python3.5/site-packages/tornado/iostream.py", line 525, in read_until_close
future = self._set_read_callback(callback)
File "/.local/lib/python3.5/site-packages/tornado/iostream.py", line 860, in _set_read_callback
assert self._read_future is None, "Already reading"
read_until_close 从套接字异步读取所有数据,直到它关闭。 read_until_close
必须调用一次,但循环会强制执行第二次调用,这就是您出现错误的原因:
- 在第一次迭代中,
read_until_close
设置streaming_callback
和 returnsFuture
以便您等待或稍后使用; - 在第二次迭代中,
read_until_close
引发异常,因为您已经在第一次迭代中设置了回调。
read_until_close
returns Future
对象,您可以 await
它使事情正常进行:
async def handle_stream(self, stream, address):
try:
await stream.read_until_close(streaming_callback=self._on_read)
except StreamClosedError:
# do something