gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:52:12 25 4
gpt4 key购买 nike

网站加载正常,但 channel 无法正常工作。在控制台中我得到:与“ws://fortests.ovh/8”的 WebSocket 连接失败:WebSocket 握手期间出错:意外的响应代码:404

服务器:Digital Ocean 上的 Ubuntu 16.04nginx 版本:nginx/1.10.0 (Ubuntu)Redis服务器v=3.2.8

我的设置.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()

消费者.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)

路由.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( channel 2)时,我也遇到了上述 404 错误。最终得到以下 nginx 配置:

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 进程的容器的名称。

关于Django channel 在本地工作但不在服务器上工作,WebSocket 握手期间出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43954981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com