App with websockets deployment error

Hey everyone can anyone help me with this problem
My application cannot access to the websocket i get an error in Dev console

(index):346 WebSocket connection to 'wss://happy-moment.live:8001/search_game/' failed: 
(anonymous) @ (index):346
(index):380 WebSocket error observed: Event {isTrusted: true, type: 'error', target: WebSocket, currentTarget: WebSocket, eventPhase: 2, …}

All my services working fine(nginx, redis, gunicorn, daphne) I am using this versions of packages:

daphne==3.0.2
Django==4.2.5
channels==3.0.5

my website conf file is

server {

    server_name happy-moment.live;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/ftpuser/main;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }

    location /ws/ {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_redirect off;
        proxy_pass http://127.0.0.1:8001;
    }
}

also i tried to listen 80 and redirect to listen 443 with specifying ssl certs
But i get an error
ERR_TOO_MANY_REDIRECTS
So that’s why i removed the http redirects to https
Website works fine in https and http (because i installed ssl using my vps panel)

here is my daphne service

[Unit]
Description=WebSocket Daphne Service
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/home/ftpuser/main
ExecStart=/home/ftpuser/venv/bin/python /home/ftpuser/venv/bin/daphne -e ssl:8001:privateKey=/etc/ssl/private.key:certKey=/etc/ssl/certificate.crt main.asgi:application

Restart=on-failure

[Install]
WantedBy=multi-user.target

Note: Also tried without specify privateKey and certKey

Redis service also listening port “127.0.0.1”, 6379

Here is my settings.py

INSTALLED_APPS = [
    'daphne',
    'chat',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'channels',
]
ASGI_APPLICATION = 'chat.routing.application'
WSGI_APPLICATION = 'main.wsgi.application'
CHANNEL_LAYERS = {
   # 'default': {
    #    'BACKEND': 'channels.layers.InMemoryChannelLayer',
   # },
      "default": {
         "BACKEND": "channels_redis.core.RedisChannelLayer",
         "CONFIG": {
             "hosts": [("127.0.0.1", 6379)],
         },
     },
}

my main/asgi.py

import os
import django
from channels.routing import get_default_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main.settings')
django.setup()
application = get_default_application()

and my chat/routing.py

from channels.auth import AuthMiddlewareStack
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import path
from channels.security.websocket import AllowedHostsOriginValidator
from django.urls import re_path
from . import consumers

application = ProtocolTypeRouter({
    'http': get_asgi_application(),
    'websocket':AllowedHostsOriginValidator(
      AuthMiddlewareStack(
            URLRouter([
            re_path(r'/chat/(?P<pk>\d+)/$', consumers.GameConsumer.as_asgi()),
            path('search_game/', consumers.SearchGameConsumer.as_asgi()),
            ])
      )
    )
})

Can anyone help me with this problem?

I even installed tshark for analizy the web traffic and found no requests to port 8001
I think the problem is in the ssl but I don’t know how to identify and fix it. I also tried to remove the ssl I installed through the vps panel (since when redirecting nttp to nttps in my website conf file) I received an error
ERR_TOO_MANY_REDIRECTS
Here is the case when I remove ssl on the panel and install Zero ssl or certbot on the hosting

website conf file

server {
    server_name happy-moment.live;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/ftpuser/main;
    }
    
     location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
   location /ws/ {
       proxy_pass http://127.0.0.1:8001;
       proxy_http_version 1.1;
       proxy_set_header Upgrade $http_upgrade;
       proxy_set_header Connection "upgrade";
       proxy_set_header Host $host;
       proxy_redirect off;
   }



    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/happy-moment.live/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/happy-moment.live/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}server {
    if ($host = happy-moment.live) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    server_name happy-moment.live;
    listen 80;
    return 404; # managed by Certbot

A few thoughts (but this is something you likely just have to poke around at until you work out what’s misaligned…)

  1. wss:// do you have your SSL certificates set up 100% for your domain?
  2. :8001 are you really hitting this port from the frontend client?
  3. /search_game/ according to the nginx snippet is this a even web socket endpoint? (Compare the location /ws/ block.)

Good luck.

Hello, Thanks for your reply
1)Ssl i installed using Control Panel (hosting provides built-in tools for installing and updating SSL certificates), also tried to remove that cert which provides cpanel, and installed a certbot, but in certbot i get an error ERR_TOO_MANY_REDIRECTS that’s why i removed the redirects from http to https in my conf file, here is my previous website conf file with certbot

I even installed the tshark- to analyze traffic and identify requests for ports 8001
but no request was made

Also tried to connect in clien side to ws

Here is my connection script in client-side

  var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
  var ws_path = ws_scheme + '://' + window.location.host + ":8001/search_game/";

  var searchGameSocket = new WebSocket(ws_path);
  
  searchGameSocket.onmessage = function(e) {
    let data = JSON.parse(e.data);
    console.log(data)
    if(data.game_id){
      window.location.href = data.url + data.game_id;
  } else {
      window.location.href = data.url;
  }

Please may I know if you fixed this issue finally and how you did it, thanks.

You’re trying to connect directly to your Daphne instance here instead of going through your nginx proxy. You probably shouldn’t be specifying the port in your connection string. If you’re accessing the site through https (port 443), then you would use the same port for the websocket. All the connections should be made via nginx.

To avoid confusion with the original post, I suggest you open a new topic to address your specific issue. Please repost this as a new topic in this category, thanks.

Note: We’re also going to need to see your Apache configuration for this path along with the JavaScript that you are using to establish the connection.

Alright. Here’s the link