Skip to content

Websocket state handling #19

Open
Open
@tbronson

Description

@tbronson

Handling of detecting when the websockets close is bugged at the moment, sessions are never cleaned up because of it.

Here are a couple patches that fix the issue:

handler.py

...
async def _receive_loop(self) -> None:
        while True:
            try:
                ws_msg = await self._socket.receive()
                self._socket._raise_on_disconnect(ws_msg)
            except WebSocketDisconnect as e:
                log.info(
                    "WebSocket connection closed: code=%s, reason=%r", e.code, e.reason
                )
                self.application.client_lost(self.connection)
...

receive does not raise when the socket is closed normally, but starlette has a private helper function to do so

...
async def send_text(self, text: str) -> None:
        try:
            await self._socket.send_text(text)
        except WebSocketDisconnect as e:
            self.on_close(e.code, e.reason)

    async def send_bytes(self, bytestream: bytes) -> None:
        try:
            await self._socket.send_bytes(bytestream)
        except WebSocketDisconnect as e:
            self.on_close(e.code, e.reason)
...

send_text and send_bytes do raise, they just needed to be put in a try block

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions