Client

You should not make an instance of the Client class yourself, rather you should listen for new connections with connection()

>>> @socket.connection
>>> async def on_connection(client: Client):
...     # Here you can use the client, register callbacks on it or send it messages
...     await client.writer.ping()
class websocket.client.Client(state, addr, port, writer, loop)[source]
Variables:
  • addr – IPv4 or IPv6 address of the client.
  • port – The port the client opened it’s socket on.
  • writer – The writer used for writing frames to the client.
closed(fn)[source]

Decorator for registering the on_closed callback.

Parameters:fn – The callback to register.

The callback should be async and take two parameters, bytes code of length 2, and str reason. This callback is called when the connection this this client is closing.

>>> @client.closed
>>> async def on_closed(code: bytes, reason: str):
...     print("Connection with client is closing for " + reason)
message(fn)[source]

Decorator for registering the on_message callback.

Parameters:fn – The callback to register.

The callback should be async and take one parameter, a WebSocketReader

This callback is called when the server receives an valid data frame, if an exception occurs after the first valid frame e.g. if an text frame contains invalid utf-8, or if it’s an invalid fragmented message, then we send the exception to the reader with set_exception().

>>> @client.message
>>> async def on_message(reader: WebSocketReader):
...     print("Got message " + await reader.get())
ping(fn)[source]

Decorator for registering the on_ping callback.

Parameters:fn – The callback to register.

If you set this callback you will override the default behaviour of sending pongs back to the client when receiving pings. If you want to keep this behaviour call pong().

The callback should be async and take two parameters, bytes payload, and int length. This callback is called when we receive a valid ping from the client.

>>> @client.ping
>>> async def on_ping(payload: bytes, length: int):
...     print("Received ping from client")
...     await self.writer.pong(length, payload)
pong(fn)[source]

Decorator for registering the on_pong callback.

Parameters:fn – The callback to register.

The callback should be async and take two parameters, bytes payload, and int length This callback is called when we receive a valid pong from the client.

>>> @client.pong
>>> async def on_pong(payload: bytes, length: int):
...     print("Received pong from client")