Django只能处理ASGI / HTTP连接,而不能处理websocket

问题描述

你好,我遇到一个错误

在来这里之前,我尝试了许多不同的方法,并研究了之前在这里打开的主题。但是无论我做什么,都会不断给我带来错误

我尝试使用daphne和uvicorn,但结果是相同的,它在本地环境中打开,但在服务器上不起作用,并显示错误

Django仅能处理Asgi / HTTP连接,而不能处理websocket

我的代码

Js代码

<script>

function connectSocket() {
var ws = new WebSocket('ws://' + window.location.host + '/ws/notification/{{request.user.id}}/')

ws.onopen = function(event){
console.log('opened',event);
}

//If there is a long onmessage codes here,I removed the code,no Syntax error

ws.onclose = function(e) {
console.error('Chat socket closed unexpectedly; reconnecting');
setTimeout(connectSocket,1000);
};

ws.onerror = function(event){
console.log('error',event);
}

// window.setInterval(function(){
// loadNotifications();
// },1000);
}
connectSocket();
</script>

Settings.py
[/JSR]
[CODE]
CHANNEL_LAYERS = {
"default": {
'BACKEND': 'channels_redis.core.RedisChannelLayer','CONfig': {
"hosts": [("redis",6379)],},}



Asgi_APPLICATION = "thesite.routing.application"

asgi

import os
import django
from channels.routing import get_default_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE','thesite.settings')

django.setup()

application = get_default_application()

Nginx

server {
listen 80;
server_name **.net www.**.net; #** = site name
root /home/ftpuser/project; 

location /static/ {

alias /home/ftpuser/project/site/static/;
}

location /media/ {
}

location / {

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-Proto $scheme;

proxy_pass http://unix:/home/ftpuser/project/thesite.sock;
}


location /ws/ {

proxy_pass http://0.0.0.0:9001;

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

proxy_redirect off;
proxy_set_header Host $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 Connection "upgrade";

更改为:

proxy_set_header Connection “upgrade”;

但是现在我给了404错误

failed: Error during WebSocket handshake: Unexpected response code: 404

我想原因 无法处理ASGI_APPLICATION参数