首页 > 解决方案 > Websocket 从连接到关闭

问题描述

我正在寻找使用 daphne 将客户端连接到 nginx 服务器,因此使用 websockets。我已经设置了我的 nginx 配置和我的 daphne.service 配置

nginx

upstream channels-backend{
server 127.0.0.1:2145;
}
server {
listen 80;
server_name 127.0.0.1 localhost;

location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
    root /home/ubuntu/My_Project;
}


location /ws/ {
    proxy_pass http://channels-backend;
    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;
}

location / {
    include proxy_params;
    proxy_pass http://unix:/run/daphne/daphne.sock;
}
}

达芙妮服务

[Unit]

Description=daphne daemon
Requires=daphne.socket
After=network.target

[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/My_Project
ExecStart=/home/ubuntu/My_Project/myp_venv/bin/daphne -p 2145 --access-log /home/ubuntu/My_project/access.log -u /run/daphne/daphne.sock --proxy-headers my_app.asgi:application

[Install]
WantedBy=multi-user.target

首先,您将看到我在 daphne.service 中绑定了端口 2145,尽管它已经配置为侦听 unix 套接字 /run/daphne/daphne.sock。我这样做是因为它仅通过侦听套接字不起作用。请问是不是权限问题。

当我尝试通过执行以下操作来测试来自客户端的连接时:

socket = new WebSocket("ws://localhost:2145/ws/");

我得到:

WebSocket { url: "ws://127.0.0.1:2145/ws/", readyState: 0, bufferedAmount: 0, onopen: null, onerror: null, onclose: null, extensions: "", protocol: "", onmessage: null, binaryType: "blob" }

在我再次检查我的套接字变量后,我得到了一个 readyState:3,它是 Connection Closed。所以从 0=Connecting 我直接到 3=Closed

WebSocket { url: "ws://localhost:2145/ws/", readyState: 3, bufferedAmount: 0, onopen: null, onerror: null, onclose: null, extensions: "", protocol: "", onmessage: null, binaryType: "blob" }

我需要知道如何摆脱显式绑定并只听 unix 套接字,以及为什么我无法通过 ws 获得打开的连接。

标签: nginxwebsocketdaphne

解决方案


推荐阅读