微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Django通道在本地但不在服务器上工作,在WebSocket握手期间出错

网站正常加载,但渠道不起作用.在控制台我得到:
与’ws://fortests.ovh/8’的WebSocket连接失败:WebSocket握手期间出错:意外响应代码404

服务器:数字海洋上的Ubuntu 16.04
Nginx版本:Nginx / 1.10.0(Ubuntu)
Redis服务器v = 3.2.8

我的settings.py:

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'asgi_redis.RedisChannelLayer',
        'CONfig': {
            'hosts': [('localhost', 6379)],
        },
        'ROUTING': 'slist.routing.channel_routing',
    }
}

wsgi.py

import os

from django.core.wsgi import get_wsgi_application

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

application = get_wsgi_application()

consumers.py

import json
from channels import Group
from channels.auth import channel_session_user_from_http, channel_session_user

from .models import Item

# Connected to websocket.connect
@channel_session_user_from_http
def ws_add(message):
    # Accept the connection
    message.reply_channel.send({"accept": True})
    # Add to the users group
    Group("users").add(message.reply_channel)

routing.py

from channels.routing import route
from tobuy.consumers import ws_add, ws_receive, ws_disconnect

channel_routing = [
    route("websocket.connect", ws_add),
    route("websocket.receive", ws_receive),
    route("websocket.disconnect", ws_disconnect),
]

JS

var socket = new WebSocket('ws://' + window.location.host + '/' + {{ active_list.id }});

Nginx设置

server {
    listen 80;
    server_name server_name fortests.ovh;

location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
    root /home/kuba1/slistproject/slistvenv/src;
}

location / {
    include proxy_params;
    proxy_pass http://unix:/home/kuba1/slistproject/slistvenv/src/slist.sock;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";

}
}

解决方法:

在docker设置中使用daphne(通道2)时,我也遇到404错误.最终得到以下Nginx conf:

map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}

upstream websocket {
        server daphne:8000;
}


server {
  listen 80 default_server;
  server_name  localhost;


  root   /var/www;
  location /static {
      index  index.html index.htm;
  }

  location / {
      root /var/www;
      try_files $uri $uri/index.html @daphne;

      expires max;
      access_log off;
  }

  location @daphne {
    proxy_pass http://websocket;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;

  }

其中daphne(第5行)是运行daphne过程的容器的名称.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐