subscription_handler
is the callback to my websockets server:
server = await websockets.serve(subscription_handler, host=websocket_host, port=websocket_port)
The original version does not work:
async def subscription_handler(websocket, path):
logger.info("New WebSocket connection")
try:
async for message in websocket:
response = await prepare_response(message)
logger.info("Sending response")
await websocket.send(response)
logger.info(f"Response sent: {response}")
except ConnectionClosedOK:
logger.info("WebSocket connection closed normally by the client.")
except ConnectionClosedError as e:
logger.warning(f"WebSocket connection closed unexpectedly: {e}")
except Exception as e:
logger.error(f"Error in subscription handler: {e}", exc_info=True)
finally:
logger.info("Subscription handler finished")
When sending the response, it throws ConnectionClosedOK
but the client does not receive the message.
Using websocket.broadcast
instead of websocket.send
fixes this:
async def subscription_handler(websocket, path):
logger.info("New WebSocket connection")
connected.add(websocket)
try:
async for message in websocket:
response = await prepare_response(message)
logger.info("Sending response")
websockets.broadcast(connected, response)
logger.info(f"Response sent: {response}")
except ConnectionClosedOK:
logger.info("WebSocket connection closed normally by the client.")
except ConnectionClosedError as e:
logger.warning(f"WebSocket connection closed unexpectedly: {e}")
except Exception as e:
logger.error(f"Error in subscription handler: {e}", exc_info=True)
finally:
logger.info("Subscription handler finished")
The client receives the message and f"Response set: {response}"
is logged.
My question is why doesn’t send
work while broadcast
does work?