Websocket disconnects after hadnshaking Django Channels

I am coding a real time chat using django and channels

My code

consumers.py:

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        room_hash = self.scope["url_route"]["kwargs"]["room_hash"]
        #self.room_group_name = self.scope["url"]["kwargs"]["hash"]

        self.send(text_data = json.dumps({
            'type':'room_hash',
             'hash': room_hash
        }))

        chat_room = Room.objects.get(hash = hash)
        print(chat_room)
        self.accept({
            'type': 'websocket.accept'
        })

    def disconnect(self):
        pass

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        print("Message is "+message)

Routing

from django.urls import path
from . import consumers

ws_urlpatterns = [
    path('ws/<str:room_hash>/', consumers.ChatConsumer.as_asgi())
]

template script:

{{room.hash|json_script:"json-roomhash"}}
<script type = "text/javascript">
   
    let room_hash = JSON.parse(document.getElementById("json-roomhash").textContent)
    let url = `ws://${window.location.host}/ws/${room_hash}/`

    const chatSocket = new WebSocket(url)

    chatSocket.onmessage = function(e){
        let data = JSON.parse(e.data)
        let hash = data.hash
        console.log(hash)
    }

    const form = document.querySelector("#form")
    console.log(form)
    form.addEventListener('submit', (e)=>{
        e.preventDefault()
        let message=  e.target.message.value
        chatSocket.send(JSON.stringify({
            'message':message
        }))
        form.reset()
    })

</script>

And it throws me this error when i try to connect to websocket by hash of the room.

raise ValueError("Socket has not been accepted, so cannot send over it") ValueError: Socket has not been accepted, so cannot send over it Exception inside application: Socket has not been accepted, so cannot send over it

I just had to add async and await so the code looks like this:

class ChatConsumer(WebsocketConsumer):
    async def connect(self):
        room_hash = self.scope["url_route"]["kwargs"]["room_hash"]
        #self.room_group_name = self.scope["url"]["kwargs"]["hash"]

        await self.send(text_data = json.dumps({
            'type':'room_hash',
             'hash': room_hash
        }))

        chat_room = Room.objects.get(hash = hash)
        print(chat_room)
        await self.accept({
            'type': 'websocket.accept'
        })

    async def disconnect(self, code):
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name,
        )

    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        print("Message is "+message)

Back to Top