“GET /rooms/friends/ HTTP/1.1” 200 654
Not Found: /ws/friends/
[26/Jul/2023 17:22:59] “GET /ws/friends/ HTTP/1.1” 404 2216
asgi.py
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
)
)
})
routing.py
from django.urls import path
from .import consumers
websocket_urlpatterns = [
path('ws/<str:room_name>/',consumers.ChatConsumer.as_asgi()),
]
websocket code:
{{ 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
+ '/', "http"
)
chatSocket.onmessage = function(e){
console.log("This is a message")
}
chatSocket.onclose = function(e){
console.log('socket closed')
}
</script>
setting.py
WSGI_APPLICATION = 'mysite.wsgi.application'
ASGI_APPLICATION = 'mysite.asgi.application'
CHANNEL_LAYERS = {
'default':{
'BACKEND':'channels.layers.InMemoryChannelLayer'
}
}
consumer.py
from channels.generic.websocket import AsyncJsonWebsocketConsumer
import json
from asgiref.sync import sync_to_async
class ChatConsumer(AsyncJsonWebsocketConsumer):
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):
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_layer
)
models.py
from django.db import models
class ChatRoom(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
urls.py
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.index,name='index'),
path('<slug:slug>/', views.chatroom, name='chatroom'),
]
Console error:
(index):11 WebSocket connection to ‘ws://localhost:8000/ws/friends/’ failed: