k1lib.kws module

Reliable websocket client and server handle functions

async k1lib.kws.serverHandle(ws: websockets.WebSocketServerProtocol, msg: str) bytes | str | None[source]

Tiny server handle addon function. Example:

async def handle_client(ws: "websockets.WebSocketServerProtocol"):
    try:
        # Continuously listen for messages from the client
        async for raw in ws:
            msg = await kws.serverHandle(ws, raw)
            if msg: # can be None
                print(f"Received message: {msg}")
                await kws.serverSend(ws, f"modified msg ({msg})")
    except websockets.exceptions.ConnectionClosed: print(f"Client at {ws.remote_address} disconnected")

# Create a WebSocket server
asyncio.get_event_loop().run_until_complete(websockets.serve(handle_client, "localhost", 8765))
asyncio.get_event_loop().run_forever()

Essentially, this function will convert the raw message received (json string with extra metadata) into your intended message sent from WsClient.

So, if you do ws.send(“abc”) on the client side, then msg variable will be “abc” on the server side.

async k1lib.kws.serverSend(ws: WebSocketServerProtocol, msg: any, retries=3, timeout=3)[source]

Msg send wrapper. Basically adds some metadata to the message. Also resends if it errors out for some reason. See serverHandle()

async k1lib.kws.serverClose(ws: WebSocketServerProtocol)[source]

Msg send wrapper. Basically adds some metadata to the message. See serverHandle()

class k1lib.kws.WsClient(url: str)[source]

Bases: object

__init__(url: str)[source]

WebSocket client that works with WsServer class. This features automatic pings and will attempt to reconnect whenever the network fails. Example:

async def main():
    async with kws.WsClient("ws://localhost:8765") as ws:
        while True:
            msg = await aioconsole.ainput("Enter a message to send (or 'exit' to quit): ")
            if msg.lower() == "exit": break
            await ws.send(msg)
            print(f"Received response: {await ws.recv()}")

asyncio.get_event_loop().run_until_complete(main())

See serverHandle() for a ws server example

Parameters

url – websocket server url, like ‘ws://localhost:8765’

property alive
async send(msg: str | bytes)[source]

Send data to server. If server offline, then will hang until server is online again. Won’t resolve until message has been sent

async recv()[source]

Receive data from server. If no data received or server offline, then hangs until some data is received