Skip to content

How to override the ping method in connection class to send a custome ping frame #1514

@river7816

Description

@river7816

I am using websockets==13.1 and have reviewed the documentation. The websockets library includes a keep-alive feature that sends an empty ByteFrame as a ping message. How can I modify the following code to send a custom message like {"op": "ping"} instead? I attempted to override the Connection class, but it didn’t work for me.

class CustomConnection(Connection):
    async def ping(self, data: bytes | None = None) -> Awaitable[float]:
        ping_message = json.dumps({"custome": "ping"})
        self.send(ping_message)
        return await super().ping(data)

async for websocket in websockets.connect(
            uri=self._base_url,
            ping_interval=self._ping_interval,
            ping_timeout=self._ping_timeout,
            close_timeout=self._close_timeout,
            max_queue=self._max_queue,
            create_connection=CustomConnection,
        ):
            try:
                payload = json.dumps(payload)
                await websocket.send(payload)
                async for msg in websocket:
                    msg = orjson.loads(msg)
                    print(msg)
            except websockets.ConnectionClosed:
                self._log.error("Connection closed, reconnecting...")

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions