[Python] How to Async send and receive websocket messages with python

Discussão em 'Python' iniciado por Stack, Julho 2, 2025.

  1. Stack

    Stack Membro Participativo

    How do you send and receive messages using pythons asyncio and the websockets library? I am using Django Channels as the socket server. So basically I am trying to send and receive from this socket server.

    I can easily send messages to my websocket server using:

    #!/usr/bin/python3

    async def main():
    uri = f"{wsPrefix}stream/{machineSerial}/?{token}"
    async with websockets.connect(uri, ping_interval = None) as websocket:
    try:
    cap = acapture.open(0)
    except:
    asyncio.sleep(1)
    cap = acapture.open(0)
    while True:
    check,frame = cap.read()
    if not websocket.open:
    print("### reconnecting ###")
    await websockets.connect(uri,ping_interval = None)
    if check:
    frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
    check, jpeg = cv2.imencode('.jpg', frame)
    frame = jpeg.tobytes()
    frame = bytearray(frame)
    await websocket.send(frame)
    await asyncio.sleep(0.05)


    if __name__ == "__main__":
    import websockets
    import asyncio
    import acapture
    import cv2
    from deviceSpecificVals import machineSerial, token
    import deviceSpecificVals.url

    urlPrefix = deviceSpecificVals.url
    wsPrefix = deviceSpecificVals.wsPrefix

    asyncio.run(main())


    But how can you add another async function here to always be listening for a message? I want the receiver to finish the script and close when it receives a 'close' message.

    I tried:

    #!/usr/bin/python3

    async def connect():
    uri = f"{wsPrefix}stream/{machineSerial}/?{token}"
    async with websockets.connect(uri, ping_interval = None) as websocket:
    return websocket


    async def rcv(websocket):
    while True:
    msg = await websocket.recv()
    print(f"< {msg}")

    async def send(websocket):
    uri = f"{wsPrefix}stream/{machineSerial}/?{token}"
    try:
    cap = acapture.open(0)
    except:
    asyncio.sleep(1)
    cap = acapture.open(0)
    while True:
    check,frame = cap.read()
    if not websocket.open:
    print("### reconnecting ###")
    await websockets.connect(uri,ping_interval = None)
    if check:
    frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
    check, jpeg = cv2.imencode('.jpg', frame)
    frame = jpeg.tobytes()
    frame = bytearray(frame)
    await websocket.send(frame)
    await asyncio.sleep(0.05)

    async def main():
    websocket = await connect()
    asyncio.ensure_future(send(websocket))
    asyncio.ensure_future(rcv(websocket))
    await asyncio.sleep(100000)

    if __name__ == "__main__":
    import websockets
    import asyncio
    import acapture
    import cv2
    from deviceSpecificVals import machineSerial, token
    import deviceSpecificVals.url

    urlPrefix = deviceSpecificVals.url
    wsPrefix = deviceSpecificVals.wsPrefix

    asyncio.run(main())


    This will not connect to websocket, it is almost as if the connect function is not returning the websocket object. I am also very new to async, and trying to understand what is happening here

    Continue reading...

Compartilhe esta Página