Skip to content

Handling WebSocket disconnects #255

Closed
@saghul

Description

When reading from a ws connection, the receive_msg function may raise WSClientDisconnectedError. The example in the documentation just returns the ws object once done:

@asyncio.coroutine
def websocket_handler(request):
    ws = web.WebSocketResponse()
    ws.start(request)

    while True:
        try:
            data = yield from ws.receive_str()
            ws.send_str(data)
        except web.WSClientDisconnectedError:
            return ws

However, when an error is produced the exception is also stored in the closing_fut: https://github.com/KeepSafe/aiohttp/blob/master/aiohttp/web.py#L833-L859 As a result, a warning is logged because nobody retrieves that exception. I guess one way to "solve" it is to do something like this:

@asyncio.coroutine
def websocket_handler(request):
    ws = web.WebSocketResponse()
    ws.start(request)

    while True:
        try:
            data = yield from ws.receive_str()
            ws.send_str(data)
        except web.WSClientDisconnectedError:
            try:
                yield from ws.wait_closed()
            except web.WSClientDisconnectedError:
                pass
            return ws

But it kinda feels wrong.

Am I missing something or should this be handled differently? Thanks a lot for aiohttp, I'm really liking it so far!

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions