【问题标题】:Django can only handle ASGI/HTTP connections, not websocketDjango 只能处理 ASGI/HTTP 连接,不能处理 websocket
【发布时间】:2021-01-21 16:10:05
【问题描述】:

您好,我遇到了一个错误。

在来这里之前,我尝试了很多不同的方式,并查看了之前在这里打开的主题。但无论我做什么,它总是给我错误。

我试过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;


}







}

【问题讨论】:

    标签: javascript django nginx gunicorn daphne


    【解决方案1】:

    哦不=(这个错误是语法错误

    proxy_set_header Connection "upgrade";
    

    改为:

    proxy_set_header Connection “upgrade”;
    

    但现在我给出 404 错误

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

    我猜是什么原因 处理 ASGI_APPLICATION 参数失败

    【讨论】:

      猜你喜欢
      • 2020-05-11
      • 2021-09-14
      • 2023-01-24
      • 2014-03-16
      • 2018-07-02
      • 1970-01-01
      • 2011-04-24
      • 1970-01-01
      • 2012-12-08
      相关资源
      最近更新 更多