Flask with SocketIO on Uwsgi and Nginx



我正在开发使用WebSockets与前端通信的Flask应用程序。它托管在nginx后面的Amazon EC2上,并由uwsgi提供服务器。

这是我用来服务然后应用程序的 uwsgi 配置:

[uwsgi]
plugins=python3,logfile
chdir=/srv/myapp/
master=true
home=/srv/myapp/.venv
module=application
callable=flask_app
uid=uwsgi
gid=myapp
socket=/srv/myapp/uwsgi.sock
chown-socket=uwsgi:myapp
chmod-socket=660
logto = /srv/myapp/logs/uwsgi.log
for-readline = /srv/myapp/.vars
env = %(_)
endfor =

以及涵盖socketio端点的nginx配置摘录:

location /socket.io/ {
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_http_version 1.1;
proxy_buffering off;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_pass http://unix:///srv/myapp/uwsgi.sock;
}

没有网络套接字,一切正常。在本地(我使用的是 Windows)一切也完美无缺 - 我只是在客户端上添加了transport: ['websockets', 'polling']以确保选择正确的协议。

在本地,我按照 Flask-SocketIO 文档中的建议运行它,并且我还安装了eventlet(我不知道为什么,但在 Windows x64 中gevent包装器在开发服务器上运行Werkzeug很糟糕)。

部署应用程序时,我只看到浏览器中websocket.js:112 WebSocket connection to 'ws://myapp.com/socket.io/?EIO=3&transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 502的错误。在服务器端,我在uwsgi日志中有以下内容:invalid request block size: 21573 (max 4096)...skip。增加缓冲区大小不会改变任何内容。

在nginx日志中,我有:*413 upstream prematurely closed connection while reading response header from upstream, client: 171.6.248.10, server: localhost,, request: "GET /socket.io/?EIO=3&transport=websocket HTTP/1.1", upstream: "http://unix:///srv/myapp/uwsgi.sock:/socket.io/?EIO=3&transport=websocket", host: "myapp.com"

我试图将这些行添加到uwsgi.ini:

gevent=1000
http-websockets=true

没有任何成功

它是什么以及如何解决?

这不是我问题的实际答案,只是一些信息

我的应用程序使用 Python 3,RedHat 提供 EPEL 的 Python3.4。尽管如此,UWSGI只能使用gevent与WebSockets一起工作。因此,正如@Miguel提到的,只有一种方法 - 使用长轮询。

溶液

最后,我将应用程序服务器更改为Gunicorn,它开箱即用地提供WebSockets。

最新更新