首页 > 解决方案 > 使用 Nginx+uwsgi+django 无法同时处理 websocket 和 xhr 请求

问题描述

我正在尝试使用 Nginx+uwsgi+django 建立一个网站,其中一项任务需要 websocket。该系统在 django 服务器(python manage.py runserver)中运行良好。但是,当我在 AWS 上使用 Nginx+uwsgi 制作时,出现了问题。虽然我修改了Nginx+uwsgi的设置,但是发现服务器无法同时处理websocket和xhr请求

具体问题如下:

1)如果我使用 启动 uwsgi uwsgi --socket :8001 --module project.wsgi --http-websockets,则可以建立 websocket,但 django 的“request.websocket”中的消息始终为 none,并且 uwsgi 日志显示warning: async call without async mode

2)接下来,我尝试在 uwsgi by 中使用异步模式uwsgi --socket :8001 --module project.wsgi --http-websockets --async 10 --ugreen。在这种情况下,websocket 运行良好,但其他 xhr 请求被阻塞,服务器无法处理,直到 websocket 结束。例如,如果一个客户端正在使用 websocket 运行任务,其他客户端甚至无法登录网络。

你能帮我解决这个问题吗?

提前致谢!

标签: djangonginxwebsocketuwsgi

解决方案


您可以根据需要将以下代码段添加到位于sites-available.

这使您可以访问 url 上的 websocketws://wsbackend/wspath/

location /ws/ {
        proxy_pass http://unix:/tmp/lcs_daphne.sock;
        proxy_http_version 1.1;

        proxy_read_timeout 86400;
        proxy_redirect     off;

        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        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;
    }

这是升级http请求到ws请求的交换协议。

您可以参考文档以获取有关使用 nginx 实现 websockets的更多信息


推荐阅读