shalakhin
shalakhin

Reputation: 4866

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?

Upvotes: 3

Views: 4230

Answers (1)

xyres
xyres

Reputation: 21789

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

Upvotes: 1

Related Questions