0

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'
5
  • Put Daphne at the top of the list for a try. Commented Jul 17, 2024 at 5:34
  • @Chukwujiobi Canon what do you mean and what should I put? Commented Jul 17, 2024 at 5:38
  • what is the full url of your websocket like are you using daphne or uvicorn? This is how i use asgi server to work with websockets, here beauty_palace is my server name. uvicorn beauty_palace.asgi:application --host 0.0.0.0 --port 7002 Commented Jul 17, 2024 at 7:53
  • @Tanveer I just used channels but I don't know how can I work the url, but the default I just use url "127.0.0.1:8000" Commented Jul 18, 2024 at 5:18
  • no, this will not work, please see this documentation channels.readthedocs.io/en/latest Commented Jul 18, 2024 at 6:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.