Skip to content

Add is_disconnected property to WebSocket#3200

Open
r266-tech wants to merge 1 commit intoKludex:mainfrom
r266-tech:feature/websocket-is-disconnected
Open

Add is_disconnected property to WebSocket#3200
r266-tech wants to merge 1 commit intoKludex:mainfrom
r266-tech:feature/websocket-is-disconnected

Conversation

@r266-tech
Copy link
Copy Markdown

Description

Adds a synchronous is_disconnected property to the WebSocket class that returns True when either the client or application state is DISCONNECTED.

Closes #2766

Motivation

When handling WebSocket connections with multiple coroutines, it's common for more than one coroutine to attempt closing the connection. Without a way to check the connection state synchronously, this leads to RuntimeError exceptions.

This property enables clean, exception-free state checking:

if not websocket.is_disconnected:
    await websocket.close()

Implementation

The property simply checks whether either client_state or application_state equals WebSocketState.DISCONNECTED — both of which are already tracked by the existing state machine in starlette/websockets.py.

Changes

  • Added is_disconnected property to WebSocket class
  • Added unit test test_is_disconnected_property

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Replace RuntimeError with WebSocketDisconnected once the socket has been disconnected

1 participant