[Django]-Django Channels – Websocket connection failed

8πŸ‘

βœ…

I think the issue is in the configuration. In the nginx, you have to specify the URL prefix, not the protocol, there is also no need to add both ws and wss. The nginx config must look similar to this

location /ws/ {
    proxy_set_header Host               $http_host;
    proxy_set_header X-Real-IP          $remote_addr;
    proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Host   $server_name;
    proxy_set_header X-Forwarded-Proto  $scheme;
    proxy_set_header X-Url-Scheme       $scheme;
    proxy_redirect off;

    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;

    proxy_pass http://127.0.0.1:8001;
}

So, to connect via a Websocket protocol, you have to access something under wss://www.<mydomain>.com:8001/ws/. For this to work, your asgi routes have to also include the ws prefix. Also, you should use as_asgi()on the consumer. (https://channels.readthedocs.io/en/stable/topics/routing.html)

application = ProtocolTypeRouter({
    'websocket': AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter([
                    path('ws/messenger/<room_id>/', ChatConsumer.as_asgi()), 
            ])
        )
    ),
})

Now you should be able to connect to wss://www.<mydomain>.com:8001/ws/messenger/1/ (don’t forget the ws!).

0πŸ‘

Finally got Django Channels working (Finally managed to get my Websocket connection working) – With many thanks to Alexandr for his assistance.

From the logs, I found the following error:
ERROR: TypeError: object.__init__() takes exactly one argument (the instance to initialize)

I forgot to append as_asgi() to the end of where I was calling my ChatConsumer. So I changed my routing path from:

path('ws/messenger/<room_id>/', ChatConsumer),

TO

path('ws/messenger/<room_id>/', ChatConsumer.as_asgi()),

And my Websocket is now open and has successfully connected! Happy days!

A big thank you again for all your help Alexandr!

πŸ‘€Jarjar95

0πŸ‘

    proxy_pass http://localhost:10001;
    proxy_set_header Host $host;
    # WebSocket support
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    # ...other WebSocket settings
πŸ‘€new-user1

Leave a comment