Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python websockets consumer and producer examples needed

http://websockets.readthedocs.io/en/stable/intro.html#consumer contains the following example:

async def consumer_handler(websocket, path):
    while True:
        message = await websocket.recv()
        await consumer(message)

and http://websockets.readthedocs.io/en/stable/intro.html#producer

async def producer_handler(websocket, path):
    while True:
        message = await producer()
        await websocket.send(message)

But there is no example for consumer() and producer() implementation or any explanation. Can somebody provide any simple example for that?

like image 392
shalakhin Avatar asked Feb 26 '26 18:02

shalakhin


1 Answers

In the first example, consumer_handler listens for the messages from a websocket connection. It then passes the messages to a consumer. In its simplest form, a consumer can look like this:

async def consumer(message):
    # do something with the message 
    

In the second example, producer_handler receives a message from a producer and sends it to the websocket connection. A producer can look like this:

async def producer():
    message = "Hello, World!"
    await asyncio.sleep(5) # sleep for 5 seconds before returning message
    return message
like image 142
xyres Avatar answered Feb 28 '26 12:02

xyres