注意事项:
- uwsgi一定不要启用多个进程,不然socketIO协商会错误,通过NGINX的负载均衡来代替
- SocketIO中配置跨域选项,防止协商错误
- uwsgi使用http模式,socket模式无法让NGINX代理websocket
- 服务端开发时可以使用socketio.run()启动服务器,同时建议通过gevent的实现方式
依赖模块(推荐通过pipenv做环境管理):
- flask
- flask-socketio
- gevent
- gevent-websocket
app.py
from flask import Flask
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, cors_allowed_origins="*")
@socketio.on('message')
def handle_message(data):
print('received message: ' + data)
@socketio.on('my event')
def handle_my_custom_event(json):
print('received json: ' + str(json))
if __name__ == '__main__':
app.run()
uwsgi.ini配置文件
[uwsgi]
master = True
socket = 127.0.0.1:5555
chmod-socket = 666
project = t-flask
home = ./.venv # 由于我使用的是pipenv做环境管理,同时启用将依赖安装在项目目录,所以需要配置这个环境选项
chdir = .
module = wsgi
callable = app
processes = 1
max-requests = 5000
pidfile = ./uwsgi.pid
daemonize = ./%(project).log
vacuum = True
nginx配置
location / {
proxy_cookie_domain domino_server nginx_server;
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://127.0.0.1:5000;
}
location /socket.io/ {
proxy_pass http://127.0.0.1:5000/socket.io/;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
}
网友评论