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: