Using daphne and websockets - show output as an when it comes

I am using daphne in Django 4.1 for a basic simple slow reply from the server.

class ExampleWebSocket(AsyncWebsocketConsumer):

    async def receive(self, text_data):
        print("Received : " + text_data)
        if (text_data == "START"):        
            await self.send_message(self)

    async def send_message(self, res):      
        for j in range(0, 10):            
            time.sleep(1) # Time it takes to retrieve some data
            await self.send(text_data=f"Data received as: {j}")
        await self.send(text_data="DONE")

Everything’s working, but my console.log is showing 1 through 10 after 10 seconds in one go and not as Data received as: n after each second.

const contactServer = () =>
{
    let socket = new WebSocket('ws://localhost:8989/test'); 
    socket.addEventListener('open', function (event)
    { 
        socket.send('START');
    }); 
     
    socket.addEventListener('message', function (event)
    { 
        console.log(event.data); 
         
        if (event.data == "DONE")
        {
            console.log('DONE socket !');
            // socket.close();
        }
    });
}

This may be the possible cause

You shouldn’t use time.sleep on an async function, use asyncio.sleep instead.

1 Like

Slightly more accurately, the statement would be await asyncio.sleep(1).

If you’ve not worked in a “Cooperative multitasking” (e.g. “async”) environment before, you might want to read Coroutines and Tasks — Python 3.11.2 documentation to get some ideas as to the underlying principles.

2 Likes

I got this working - thanks.

Side Note : daphne doesn’t seem to run with Python 3.11 - but it runs on Python 3.10 on my Windows 11 machine.

Technically, the 3.11 issue is a Twisted-related issue, not Daphne. Apparently, it can be gotten to run. See Error install Twisted (dependency twisted-iocpsupport 1.0.2 in Python 3.11.1) · Issue #11802 · twisted/twisted · GitHub

1 Like