I'm struggling why still insist not being connected my WebSocket using Django, I've used laragon as Mysql and I just used my local database, and I just want to try first before saving to database it if it works or not but I getting an error. Did I forgot something?
Not Found: /ws/socket-server/
so I have this format
and I have error in my html url on line const chatSocket = new WebSocket(url)
html
$(document).ready(function () {
let url = `ws://${window.location.host}/ws/socket-server/`
const chatSocket = new WebSocket(url)
chatSocket.onmessage = function(e){
let data = JSON.parse(e.data)
console.log('Data:', data)
if(data.type === 'chat'){
let messages = document.getElementById('messages')
messages.insertAdjacentHTML('beforeend', `<div> <p>${data.message}</p></div>`)
}
}
});
main/routing.py
from django.urls import re_path
from main import consumers
websocket_urlpatterns = [
re_path(r'ws/socket-server/', consumers.ChatConsumer.as_asgi())
]
main/consumers.py
import json
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.room_group_name = 'test'
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type':'chat_message',
'message':message
}
)
def chat_message(self, event):
message = event['message']
self.send(text_data=json.dumps({
'type':'chat',
'message':message
}))
tev/asgi.py
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import main.routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tev.settings')
application = ProtocolTypeRouter({
'http':get_asgi_application(),
'websocket':AuthMiddlewareStack(
URLRouter(
main.routing.websocket_urlpatterns
)
)
})
settings.py
INSTALLED_APPS = [
....
'channels',
]
ASGI_APPLICATION = 'tev.asgi.application'
beauty_palaceis my server name.uvicorn beauty_palace.asgi:application --host 0.0.0.0 --port 7002