0

I'm trying to create a websocket server on which a single client will push its messages (I know this is not the usual way to use websocket but this part is not my choice). To this end, I'm using python 3.7 and websockets 7.0.

My issue is: Numerous messages pushed by the client are not received by the server. Here is the simple code I'm using.

import asyncio
import websockets


async def get_tag_data(websocket, path):
    # print('received')
    data = await websocket.recv()
    print(data)


loop = asyncio.get_event_loop()
anchors_server = websockets.serve(get_tag_data, 'localhost', 9001)
loop.run_until_complete(asyncio.gather(anchors_server))
loop.run_forever()

Conversely, when I try the python-websocket-server (which uses threads for reception), all my messages are correctly received.

As far as I understand asyncio & websockets, it is supposed to manage backpressure: messages sent while the server is busy (to process older messages) are "buffered" and will be treat shortly....

What am I missing? Do I need to thread the websocket reception with asyncio to avoid losing messages?

Thank you for your answers!

2 Answers 2

1

Ok, I get it. My function was running only once, next messages was not buffered. The following code resolve the issue :

import asyncio
import websockets
import signal
import sys

async def get_tag_data(websocket, path):
    while True:
        async for data in websocket:
            print(data)

loop = asyncio.get_event_loop()
anchors_server = websockets.serve(get_tag_data, '', 9001)
loop.run_until_complete(asyncio.gather(anchors_server))
loop.run_forever()

note the

while True:
    async for data in websocket
Sign up to request clarification or add additional context in comments.

Comments

1

Shoud be without while loop.

import asyncio
import websockets
import signal
import sys

async def get_tag_data(websocket, path):
    async for data in websocket:
        print(data)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.