protocol/logging: workaround for asyncio's inability to detect connection closes on writes

This commit is contained in:
Sebastien Bourdeauducq 2015-10-16 21:28:39 +08:00
parent f332c1d3cc
commit 6c856025cc

View File

@ -117,11 +117,19 @@ class LogForwarder(logging.Handler, TaskObject):
try:
reader, writer = await asyncio.open_connection(self.host,
self.port)
detect_close = asyncio.ensure_future(reader.read(1))
writer.write(_init_string)
while True:
message = await self._queue.get() + "\n"
writer.write(message.encode())
await writer.drain()
# HACK: detect connection termination through the completion
# of a read operation. For some reason, write/drain operations
# on a closed socket do not raise exceptions, but print
# "asyncio:socket.send() raised exception."
if detect_close.done():
await asyncio.sleep(self.reconnect_timer)
break
except asyncio.CancelledError:
return
except: