Search code examples
javascriptdjangonginxgunicorndaphne

Django can only handle ASGI/HTTP connections, not websocket


Hello I am getting a error.

Before coming here, I tried many different ways and looked at the topics that were opened here before. But whatever I do, it keeps giving me errors.

I tried daphne and uvicorn but the result is the same, it opens in local environment but it does not work on the server and gives this error:

Django can only handle ASGI / HTTP connections, not websocket

My Codes:

Js Code:

<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;


}







}

Solution

  • Oh No =( this error is the syntax error

    proxy_set_header Connection "upgrade";
    

    Change to :

    proxy_set_header Connection “upgrade”;
    

    But now ı give the 404 eror

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

    I guess the reason Failure to process ASGI_APPLICATION parameter