Why does my Django application using websocket not work when deployed?

So I created an online chat site using Django and Javascript and I'm having trouble making it work when I deploy it on a live server. It works perfectly fine locally though. Whenever I try to send a message on the chat on the deployed server I get a "Firefox can’t establish a connection to the server at ws://url".

I think this is a websocket issue.

My asgi.py file is as follows :

import os
import rooms.routing

from django.core.asgi import get_asgi_application
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter


os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webchat.settings')

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": AuthMiddlewareStack(
        URLRouter(
            rooms.routing.websocket_urlpatterns
        )
    )
})

And my consumers.py file :

import json
from channels.generic.websocket import AsyncWebsocketConsumer
from asgiref.sync import sync_to_async
from django.contrib.auth.models import User
from .models import Room, Message

class Consumer(AsyncWebsocketConsumer):
    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
        )

    async def receive(self, text_data):
        data=json.loads(text_data)
        msg=data['message']
        username=data['username']
        room=data['room']
        if msg.isspace()==False and msg != "" : #On ne veut pas stocker ou envoyer les messages vides ou ne contenant que des espaces
            await self.storeMsg(msg,username,room)
            await self.channel_layer.group_send(
                self.room_group_name, {
                    'type': 'chatmsg',
                    'message': msg,
                    'username':username,
                    'room':room,
                }
            )

    async def chatmsg(self,event):
        msg=event['message']
        username=event['username']
        room=event['room']
        await self.send(text_data=json.dumps({
            'message': msg,
            'username':username,
            'room':room,
        }))

I don't know what more files are relevant for this issue.

The problem arises only when I try to deploy it, everything related to websockets works fine locally.



Comments

Popular posts from this blog

Spring Elasticsearch Operations

Object oriented programming concepts (OOPs)

Network Error and Timeout on Authorize.net JS