Web Socket connection failed

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

Couple different things:

has an error - it should be kwargs, not kwarges. (Not at all related to the current error, but does need to be corrected.)

Also, how are you running this? Your application object identifies the websocket only - how/where are you running your Django instance?
(Side note: If you’re running Daphne to only run the websocket handler and you’re running Django in a completely separate process, there are other changes necessary to your routing.py file. If that’s the case, please post your complete routing.py file.)

I’m running Django on local host server,
I installed Dephne , and I add it to INSTALLED_APP in settings , and I still got the same error
here is routing file in my project

routing.py

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

import chat.routing

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

in terminal I got this error

TypeError: object ChatRoomConsumer can't be used in 'await' expression
WebSocket DISCONNECT /ws/chat/room/ [127.0.0.1:63868]

consumers.py

class ChatRoomConsumer(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()
        # 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)

Please post the full traceback from that error. Also please post your asgi.py file.

(venv) C:\Users\olaro\OneDrive\Masaüstü\Working area\django_project>python manage.py runserver      
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
October 26, 2023 - 13:41:57
Django version 4.2.4, using settings 'core.settings'
Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
HTTP GET /chat/room/ 200 [0.02, 127.0.0.1:64665]
WebSocket HANDSHAKING /ws/chat/room/ [127.0.0.1:64667]
Exception inside application: object ChatRoomConsumer can't be used in 'await' expression
Traceback (most recent call last):
  File "C:\Users\olaro\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\staticfiles\handlers.py", line 101, in __call__
    return await self.application(scope, receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\olaro\AppData\Local\Programs\Python\Python311\Lib\site-packages\channels\routing.py", line 62, in __call__
    return await application(scope, receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\olaro\AppData\Local\Programs\Python\Python311\Lib\site-packages\channels\sessions.py", line 47, in __call__
    return await self.inner(dict(scope, cookies=cookies), receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\olaro\AppData\Local\Programs\Python\Python311\Lib\site-packages\channels\sessions.py", line 263, in __call__
    return await self.inner(wrapper.scope, receive, wrapper.send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\olaro\AppData\Local\Programs\Python\Python311\Lib\site-packages\channels\auth.py", line 185, in __call__
    return await super().__call__(scope, receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\olaro\AppData\Local\Programs\Python\Python311\Lib\site-packages\channels\middleware.py", line 24, in __call__
    return await self.inner(scope, receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\olaro\AppData\Local\Programs\Python\Python311\Lib\site-packages\channels\routing.py", line 116, in __call__
    return await application(
           ^^^^^^^^^^^^^^^^^^
TypeError: object ChatRoomConsumer can't be used in 'await' expression
WebSocket DISCONNECT /ws/chat/room/ [127.0.0.1:64667]

asgi.py

"""
ASGI config for chatbot project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""

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


os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings")


application = get_asgi_application()

You’ve got some things in the wrong files.

The routing.py should have your websocket_urlpatterns definition.

The definition for the application object belongs in the asgi.py file.

I suggest you review the docs at Tutorial Part 2: Implement a Chat Server — Channels 4.0.0 documentation for seeing what should be in each file.

Welcome @paakwasi317 !

What information do you have that shows that as being used?

That’s not what’s shown in the docs for the asgi.py at Tutorial Part 1: Basic Setup — Channels 4.0.0 documentation or in the example at Routing — Channels 4.0.0 documentation for the "http" entry in the ProtocolTypeRouter.

The application object in asgi.py should be an instance of ProtocolTypeRouter, not an application.

1 Like

Hi Ken,

I just realised that I was wrong. What I implemented in my asgi.py is not functional as I thought it was. What you suggested is the right answer. I have deleted my suggestion. Sorry for the misinformation

1 Like

hey I’m getting the same error what changes have you made in the asgi.py file?

Welcome @maxpayne !

If you’re getting a “Web Socket connection failed” message, there are many different possible reasons.

If you’re looking for assistance with that, please open a new topic, posting at least the contents of your asgi.py, routing.py, and the portion of your JavaScript code that is attempting to open the websocket.

Additionally, describe how you’re running your server, and post the command line / scripts being used to do so. (Is this a development environment or your deployment environment?)