Socket

Usage

>>> loop = asyncio.get_event_loop()
>>> socket = WebSocketServer("localhost", 3001, loop=loop)
...
>>> @socket.connection
>>> async def on_connection(client: Client):
...     logger.info(f'Connection from {client.addr, client.port}')
...     logger.info(f'All clients: {socket.clients}')
...
...     @client.message
...     async def on_message(reader: WebSocketReader):
...         await client.writer.send(await reader.get())
...
>>> with socket as server:
...     print(f'Serving on {server.sockets[0].getsockname()}')
...     loop.run_forever()
...
>>> loop.close()
class websocket.server.WebSocketServer(addr, port, certs=None, loop=None, timeout=120)[source]
Variables:
  • addr – The server IPv4 or IPv6 address.
  • port – The server port.
  • timeout – The timeout in seconds for clients, if they don’t respond to pings. Set to 0 to disable heartbeat.
  • certs – SSL certificates
  • clients – All of the connected clients.
  • loop – The event loop to run in.
connection(fn)[source]

Decorator for registering the on_connection callback.

Parameters:fn – The callback to register.

The callback should be async and take one parameter, Client. This callback is called when a new client connects with the websocket.

>>> @socket.connection
>>> async def on_connection(client: Client):
...     for other_client in socket.clients.vals():
...         other_client.writer.send("New client connected.")
...     
...     @client.message
...     async def on_message(reader: WebSocketReader):
...         await client.writer.send(await reader.get())
disconnect_client(client, code=b'\x03\xe8', reason='')[source]

This method is the only clean way to close a connection with a client.

>>> @socket.connection
>>> async def on_connection(client: Client):
...     print("Client connected, disconnecting it...")
...     socket.disconnect_client(client)
Parameters:
  • client – The client to disconnect from the server.
  • code (bytes) – The code to close the connection with, make sure it is valid. Default is websocket.reasons.Reasons.NORMAL.value.code
  • reason (str) – The reason for closing the connection, may be ‘’. Should not be longer than 123 characters.
wait(fut, timeout)[source]

Helper method for creating a future that times out after a timeout.

Parameters:
  • fut – The future to time.
  • timeout – The timeout in seconds.
Returns:

future