Websocket Connection Failed after some moment of connection

I am able to establish handshake when my websocket connects but then it disconnects right after sending first message from the server to the client.What I noticed is even after the connection fails the server keeps sending to the client, but re-establish handshake.Hence the connection is closed at this point. And also connection fails when another client tries connecting the same websocket.

What I’m trying to achieve is when the websocket connects i want to be calling the spotify api to keep sending music data to client.

class SpotifyConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        id = self.scope['url_route']["kwargs"]['pk']
        self.room_group_name = id[1:]
        await self.channel_layer.group_add(self.room_group_name, self.channel_name)
        await self.accept()
        # do something
    async def receive(self, text_data=None):
        id_session = self.scope['url_route']['kwargs']['pk']
        id_session = id_session[1:]
        data = json.loads(text_data)
        _stream = data['message']
        message = {
            "id": id_session,
            "can_stream": _stream
        await self.channel_layer.group_send(self.room_group_name,{"type": "send.stream","message": message})

    async def send_stream(self,event):
        endpoint = "player/currently-playing/"
        data = event["message"]
        can_stream = data["can_stream"]
        id_session = data["id"]
        if self.websocket_connect:
            while can_stream:
                response = await sync_to_async(spotify_api_calls)(session_id=id_session,endpoint=endpoint)
                while "error" in response or "item" not in response:
                if 'item' in response:
                    item = response.get('item')
                    duration = item.get('duration_ms')
                    progress = response.get('progress_ms')
                    album_cover = item.get('album').get('images')[0].get('url')
                    is_playing = response.get('is_playing')
                    song_id = item.get('id')
                    artist_name_string = ""
                for i, artist in enumerate(item.get('artists')):
                    if i > 0:
                        artist_name_string += ", "
                    name = artist.get('name')
                    artist_name_string += name
                response = {
                    'title': item.get('name'),
                    'artist': artist_name_string,
                    'duration': duration,
                    'time': progress,
                    'image_url': album_cover,
                    'is_playing': is_playing,
                    'id': song_id
                    await self.send(text_data=json.dumps({"message":response}))
                except Exception as e:
    async def disconnect(self, code):
        await self.channel_layer.group_discard(self.room_group_name,self.channel_name)
        raise StopConsumer()


ws_urlpatterns =[

websocket connection at client

    let streamSong = ()=>{
        const streamSocket = new WebSocket(`ws://${id}/`)

        streamSocket.onopen = (e) =>{
                'message': true
        streamSocket.onmessage = (e) =>{
            const data = JSON.parse(e.data)

        streamSocket.onclose = (e) =>{


Are you running the consumer in Daphne, uvicorn, or some other ASGI container?

If you’re running this in Daphne, what messages are you seeing on the server’s console?
At a minimum you should be seeing the connect and disconnect messages. Is there anything else showing up? If there’s a problem within your consumer, you should be seeing the errors with (hopefully) a traceback.

Have you examined the data being passed through the websocket? (The easiest way I know of to do this is by using the browser’s developer tools - the network tab will show you the message frames being passed.)

Do you have a simpler consumer working? One that doesn’t try to integrate an external source of data?

Note, do not do this:

You need to use await asyncio.sleep(5)

Also, you don’t want to do this:

From the docs:

The generic consumers below do this for you, so this is only needed if you are writing your own consumer class based on AsyncConsumer or SyncConsumer .