带有 Django 通道的 Websocket 不起作用,连接失败

Eu *_*Chi 6 django websocket redis django-channels daphne

你好很棒的人!

我创建了一个聊天室django-channels。每次我在生产环境中尝试通过网络套接字连接到我的聊天室时,它都会失败。在本地它可以正常工作。

我在digitalocean上主持

点冻结:

channels==2.1.2
channels-redis==2.3.0
daphne==2.2.1
'''
Run Code Online (Sandbox Code Playgroud)

我已经安装了redis-server

sudo apt-get install redis-server
Run Code Online (Sandbox Code Playgroud)

这是我的设置。

INSTALLED_APPS = [
    # '''
   'channels',
    # '''
] 
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
        },
    },
}
ASGI_APPLICATION = "project_name.routing.application"
Run Code Online (Sandbox Code Playgroud)

这是我的asgi.py身边wsgi.py

import os
import django
from channels.routing import get_default_application

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings")
django.setup()
application = get_default_application()
Run Code Online (Sandbox Code Playgroud)

这是我的 project_folder.rounting.py

application = ProtocolTypeRouter({
    'websocket':AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter([
                # my urls
            ])
        )
    )
})
Run Code Online (Sandbox Code Playgroud)

我一直在 firefox 和其他浏览器中得到类似的东西:

Firefox 无法与位于 wss://www.domain_name.com/url-to/1/XBv​​Zjr2pqdf6fhy/ 的服务器建立连接

但是它在本地工作。

更新

这是我的js

var loc = window.location;
var wsStart = loc.protocol == "https:" ? "wss://" : "ws://"
var endpoint = wsStart + loc.host + loc.pathname
var socket = new ReconnectingWebSocket(endpoint);

socket.onmessage = function(e){
    // code
}
Run Code Online (Sandbox Code Playgroud)

Eu *_*Chi 13

我终于解决了这个问题,并wssslwss://.

对于那些面临同样问题的人。

请注意,我使用

  • gunicorn作为仅用于http请求的Web 服务器
  • daphne作为ws网络套接字的网络服务器
  • nginx 作为反向代理

asgi.py

import os
import django
from channels.routing import get_default_application

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
django.setup()
application = get_default_application()
Run Code Online (Sandbox Code Playgroud)

settings.py

ASGI_APPLICATION = "project.routing.application"

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [(os.environ.get('REDIS_HOST', 'localhost'),6379)],
        },
    },
}
Run Code Online (Sandbox Code Playgroud)

asgi用 django设置后,我supervisorctl用来继续daphne运行。创建一个文件daphne_asgi.conf/etc/supervior/conf.d/

daphne_asgi.conf

[program:asgi_daphne]

directory=/path/to/your/project

command=/executable/path/to/daphne --bind 0.0.0.0 --port 8010 project.asgi:application
# 0.0.0.0 ip of your website
# I choose the port 8010 for daphne

stdout_logfile=/path/to/log/daphne.log

autostart=true

autorestart=true

redirect_stderr=true
Run Code Online (Sandbox Code Playgroud)

运行以下命令更新启动守护进程

sudo supervisorctl reread
sudo supervisorctl update
Run Code Online (Sandbox Code Playgroud)

这里是配置 nginx

map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}
upstream websocket {
    server 0.0.0.0:8010;
}
Run Code Online (Sandbox Code Playgroud)

daphne中使用的主机和端口... --bind 0.0.0.0 --port 8010

#redirection to a https
server {
    listen 80;
    server_name 0.0.0.0 example.com www.example.com;
    client_max_body_size 10M;
    return 301 https://www.example.com$request_uri;
}

server {
    listen 443 ssl default_server;
    server_name www.example.com;
    client_max_body_size 10M;

    # ssl configuration
    ...

    # normal http request, I use .sock
    location / {
        include proxy_params;
        proxy_pass http://unix:/path/to/project.sock;
    }

    # ws request /ws/
    location /ws/ {
        proxy_pass http://websocket;

         # this magic is needed for WebSocket
        proxy_http_version  1.1;
        proxy_set_header    Upgrade $http_upgrade;
        proxy_set_header    Connection $connection_upgrade;
        proxy_set_header    Host $http_host;
        proxy_set_header    X-Real-IP $remote_addr;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,我/ws/在 ws 网址中添加了

application = ProtocolTypeRouter({

    'websocket':AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(
                [
                    url(r'^ws/$', HelloConsumer),
                ]
            )
        )
    )
})
Run Code Online (Sandbox Code Playgroud)