# Web Socket connection failed

**URL:** <https://forum.djangoproject.com/t/web-socket-connection-failed/24784>\
**Category:** Async/Channels\
**Created:** [October 25, 2023, 6:18pm UTC](https://forum.djangoproject.com/t/web-socket-connection-failed/24784 "2023-10-25T18:18:19Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![oulaKhaled](https://avatars.discourse-cdn.com/v4/letter/o/c5a1d2/32.png) [@oulaKhaled](https://forum.djangoproject.com/u/oulaKhaled)\
**Post date:** [October 25, 2023, 6:18pm UTC](https://forum.djangoproject.com/t/web-socket-connection-failed/24784/1 "2023-10-25T18:18:19Z")

</div>

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

```auto
def room(request, room_name):
    return render(request, "chatroom.html", {"room_name": room_name})

```

> routing.py

```auto
websocket_urlpatterns = [
    re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatRoomConsumer.as_asgi()),
]

```

> consumers.py

```auto
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

```auto
 <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

```auto
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

```auto

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**

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [October 25, 2023, 6:40pm UTC](https://forum.djangoproject.com/t/web-socket-connection-failed/24784/2 "2023-10-25T18:40:35Z")

</div>

Couple different things:

- You’re not showing `daphne` as being in your INSTALLED\_APPS. (See [Installation — Channels 4.0.0 documentation](https://channels.readthedocs.io/en/latest/installation.html#installation))

- This:

> [@oulaKhaled](#):
>
> `self.room_name = self.scope["url_route"]["kwarges"]["room_name"]`

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.)

---

<div class="post-metadata">

**Author:** ![oulaKhaled](https://avatars.discourse-cdn.com/v4/letter/o/c5a1d2/32.png) [@oulaKhaled](https://forum.djangoproject.com/u/oulaKhaled)\
**Post date:** [October 26, 2023, 10:30am UTC](https://forum.djangoproject.com/t/web-socket-connection-failed/24784/3 "2023-10-26T10:30:20Z")

</div>

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

```auto
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

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

```

> consumers.py

```auto
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)

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [October 26, 2023, 11:08am UTC](https://forum.djangoproject.com/t/web-socket-connection-failed/24784/4 "2023-10-26T11:08:20Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![oulaKhaled](https://avatars.discourse-cdn.com/v4/letter/o/c5a1d2/32.png) [@oulaKhaled](https://forum.djangoproject.com/u/oulaKhaled)\
**Post date:** [October 26, 2023, 1:08pm UTC](https://forum.djangoproject.com/t/web-socket-connection-failed/24784/5 "2023-10-26T13:08:38Z")

</div>

```auto
(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

```auto
"""
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()

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [October 26, 2023, 11:04pm UTC](https://forum.djangoproject.com/t/web-socket-connection-failed/24784/6 "2023-10-26T23:04:01Z")

</div>

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](https://channels.readthedocs.io/en/stable/tutorial/part_2.html) for seeing what should be in each file.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [February 5, 2024, 11:05pm UTC](https://forum.djangoproject.com/t/web-socket-connection-failed/24784/8 "2024-02-05T23:05:21Z")

</div>

Welcome @paakwasi317 !

> [@paakwasi317](#):
>
> That is, correct import should be `from channels.routing import get_default_application`

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](https://channels.readthedocs.io/en/latest/tutorial/part_1.html) or in the example at [Routing — Channels 4.0.0 documentation](https://channels.readthedocs.io/en/latest/topics/routing.html) for the `"http"` entry in the `ProtocolTypeRouter`.

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

---

<div class="post-metadata">

**Author:** ![paakwasi317](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/paakwasi317/32/18979_2.png) [@paakwasi317](https://forum.djangoproject.com/u/paakwasi317)\
**Post date:** [February 5, 2024, 11:33pm UTC](https://forum.djangoproject.com/t/web-socket-connection-failed/24784/9 "2024-02-05T23:33:11Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![maxpayne](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/maxpayne/32/22583_2.png) [@maxpayne](https://forum.djangoproject.com/u/maxpayne)\
**Post date:** [July 13, 2024, 1:52pm UTC](https://forum.djangoproject.com/t/web-socket-connection-failed/24784/10 "2024-07-13T13:52:23Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [July 13, 2024, 2:39pm UTC](https://forum.djangoproject.com/t/web-socket-connection-failed/24784/11 "2024-07-13T14:39:40Z")

</div>

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?)
