Simplified websockets keep-alive logic. Just wait on recv() and clean up the websocket in case of a ConnectionClosed exception

This commit is contained in:
Fabio Manganiello 2018-05-06 11:38:24 +02:00
parent 177a359e4a
commit 2483c6d612

View file

@ -26,8 +26,6 @@ class HttpBackend(Backend):
-d '{"type":"request","target":"nodename","action":"tts.say","args": {"phrase":"This is a test"}}' \ -d '{"type":"request","target":"nodename","action":"tts.say","args": {"phrase":"This is a test"}}' \
http://localhost:8008/execute """ http://localhost:8008/execute """
websocket_ping_tries = 3
websocket_ping_timeout = 60.0
hidden_plugins = { hidden_plugins = {
'assistant.google' 'assistant.google'
} }
@ -151,29 +149,13 @@ class HttpBackend(Backend):
async def register_websocket(websocket, path): async def register_websocket(websocket, path):
logging.info('New websocket connection from {}'.format(websocket.remote_address[0])) logging.info('New websocket connection from {}'.format(websocket.remote_address[0]))
websocket.remaining_ping_tries = self.websocket_ping_tries
self.active_websockets.add(websocket) self.active_websockets.add(websocket)
while True: try:
try: await websocket.recv()
waiter = await websocket.ping() except websockets.exceptions.ConnectionClosed:
await asyncio.wait_for(waiter, timeout=self.websocket_ping_timeout) logging.info('Websocket client {} closed connection'.format(websocket.remote_address[0]))
time.sleep(self.websocket_ping_timeout) self.active_websockets.remove(websocket)
except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed) as e:
close = False
if isinstance(e, asyncio.TimeoutError):
websocket.remaining_ping_tries -= 1
if websocket.remaining_ping_tries <= 0:
close = True
else:
close = True
if close:
logging.info('Websocket client {} closed connection'
.format(websocket.remote_address[0]))
self.active_websockets.remove(websocket)
break
loop = asyncio.new_event_loop() loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop) asyncio.set_event_loop(loop)