I’ve been trying to create a chat app using websocket , But I got WebSocket connection to ‘ws://127.0.0.1:8000/ws/chat/room/’ failed:
I’m not using Redis for implementing Django channels, İt is just a simple chat app runs on local server host
views.py
def room(request, room_name):
return render(request, "chatroom.html", {"room_name": room_name})
routing.py
websocket_urlpatterns = [
re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatRoomConsumer.as_asgi()),
]
consumers.py
class ChatRoomConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope["url_route"]["kwarges"]["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()
# to know which group we should send to
await self.channel_layer.group_send(
self.room_group_name,
{
"type": "tester_message",
"tester": "hello world",
},
)
async def tester_message(self, event):
tester = event["tester"]
await self.send(text_data=json.dumps({"tester": tester}))
async def disconnect(self, close_code):
await self.channel_layer.group_discard(self.room_group_name, self.channel_name)
chatroom.html
<div id="user-hello">
</div>
<!-- convert an object into a JSON object -->
{{room_name|json_script:"room-name"}}
<script>
// convert a JSON object in text format to js object that can be used
const roomName=JSON.parse(document.getElementById('room-name').textContent);
//create websocket connection script
const chatSocket=new WebSocket(
'ws://' +
window.location.host +
'/ws/chat/' +
roomName +
'/'
);
//receive a massege
chatSocket.onmessage=function(e){
const data=JSON.parse(e.data)
console.log(data);
document.querySelector('#user-hello').innerHTML=(data.tester)
}
</script>
settings.py
INSTALLED_APPS = [
"channels",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"chat",
]
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
ASGI_APPLICATION = "core.routing.application"
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels.layers.InMemoryChannelLayer",
}
}
core/routing.py
application = ProtocolTypeRouter(
{
"websocket": AuthMiddlewareStack(URLRouter(chat.routing.websocket_urlpatterns)),
}
)
in terminal I got this error : [25/Oct/2023 20:27:52] “GET /chat/room/ HTTP/1.1” 200 1865
Not Found: /ws/chat/room