Skip to content

Server side: keep connection open when client incorrectly disconnects #1353

@Time0o

Description

@Time0o

In the docs there are ample examples showing how a client can reopen a connection after loosing it, but what about the other way around? I am writing a server that should allow for clients to reconnect after a websockets.ConnectionClosedError has been thrown. This seems like it should be a common use case. Is it possible? If so, how? My server code looks something like this:

class MyServer:
    async def _ws_handler(self, ws):
            try:
                async for data in ws:
                    pass # TODO: do something

            except websockets.ConnectionClosedOK:
                pass

            except websockets.ConnectionClosedError as e:
                pass # TODO: reconnect?

    def serve(self):
        return websockets.serve(self._ws_handler, MY_HOST, MY_PORT)

I tried to simpy wrap the try ... catch inside the handler in a while loop but that does not work since an asyncio.exceptions.InvalidStateError will be thrown once the client reconnects.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions