Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RuntimeError: Unexpected ASGI message 'websocket.send', after sending 'websocket.close'

  • I am trying to build a chat server with two websocket endpoints. One for the room owners to create_room and second for others who wants to join the room.
  • I have 'Room' and 'RoomManager' classes. Room has list of members, and other room info. where as 'RoomManager' helps in creating rooms and accepting people into the room.
  • when a user tries to enter the room with room_id i am sending a request to the room_owner whether to add the member to the room. When user accepts I am adding the member to the list of members in the room.
  • when a new user tries to enter a room and the owner accept it (by sending 'yes') I wanted to broadcast "xxxx has entered the room". When I try to broadcast it shows this error "RuntimeError: Unexpected ASGI message 'websocket.send', after sending 'websocket.close' ". This is the link to repo. I heard of sending ping pong framesbut did not find docs to implement it.

Files explanation in repo:

  • app.py : contains http and websocket endpoints

  • room_manager.py : has Room and RoomManager classes.

  • connection_manger.py: default connection manager provided by fastapi docs. Used to store temporary connections before user is part of any room.

This is the link to the cmd log.

like image 387
NANDU KISHORE Avatar asked Mar 22 '26 04:03

NANDU KISHORE


1 Answers

The error "RuntimeError: Unexpected ASGI message 'websocket.send', after sending 'websocket.close'" literally means that you are trying to send a message on a connection that was closed. From what I understand from your question you are keeping a list of users that are part of a room when a user enters the room and you are broadcasting this welcome message to all the other users of the room. But what if a user has disconnected or the underlying connection of a particular user s closed? In this case you'll get the above mentioned error.

What can solve this problem is you should always check for connection closed exception while reading/ writing messages on a connection and should mark the user disconnected if such exception occurs.

like image 198
Mayank Gupta Avatar answered Mar 23 '26 18:03

Mayank Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!