I am working on a demo chat application as part of my learning process with Django Channels and WebSockets. My goal is to establish real-time communication using WebSockets, but I’m facing an issue where the connection to the WebSocket fails. In the browser console, I consistently see an error message indicating that the WebSocket connection could not be established. Despite setting up the necessary consumers, routing, and ASGI configurations, the WebSocket connection doesn’t seem to go through, and I’m unable to proceed with the real-time messaging functionality. In the console it shows me:
WebSocket connection to 'ws://127.0.0.1:8000/ws/friends/' failed:
(anonymous) @ friends/:12
This is my consumers.py file
from channels.layers import get_channel_layer
from channels.generic.websocket import AsyncWebsocketConsumer
class ChatConsumer(AsyncWebsocketConsumer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.channel_layer = get_channel_layer()
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat%s' % self.room_name
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
This is my routing.py file
from django.urls import path
from . import consumers
websocket_urlpatterns = [
path('ws/<str:room_name>/',consumers.ChatConsumer.as_asgi())
]
and my asgi.py file
import os
from django.core.asgi import get_asgi_application
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter,URLRouter
import chatapp.routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
application = ProtocolTypeRouter({
'http':get_asgi_application(),
'websocket':AuthMiddlewareStack(
URLRouter(
chatapp.routing.websocket_urlpatterns
)
)
})
The frontend side code is this:
{{ chatroom.slug|json_script:"json-chatroomname" }}
<script>
const chatRoomname = JSON.parse(document.getElementById('json-chatroomname').textContent)
const chatSocket = new WebSocket(
'ws://'
+window.location.host+'/ws/'
+chatRoomname
+'/'
)
chatSocket.onmessage = function(e){
console.log('This is a message')
}
chatSocket.onclose = function(e){
console.log('Socket closed')
}
</script>