Nginx + socketio:未到达的事件

时间:2017-09-18 23:36:34

标签: python nginx socket.io gunicorn flask-socketio

我想用socket io将事件发送到烧瓶服务器。但是,当我通过nxginx代理部署我的应用程序时,事件不会到达。

My Flask服务器app.py如下所示:

from flask_socketio import SocketIO

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

@app.route('/')
def index():
    return "this is the index function"

@socketio.on('message')
def handle_message(message):
    print('received message: ' + message)

if __name__ == '__main__':
    socketio.run(app,debug=True)

事件从客户端发送,如下所示:

 var socket = io('http://my.ip.address.it');
 ...
 socket.emit('message', 'here is my message 1');

当我在localhost上部署我的服务器时,这是有效的。但是当我通过nginx将它部署在EC2实例上时,从客户端发出的事件偶尔会到达。

我的 nginx 代理配置如下所示:

server {
    listen 80;
    server_name my.ip.add.it;

    location / {
        include proxy_params;
        proxy_pass http://127.0.0.1:8000;
    }

    location /socket.io {
        include proxy_params;
        proxy_http_version 1.1;
        proxy_buffering off;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_pass http://127.0.0.1:8000/socket.io;
    }
}

我开始使用这样的服务器应用程序:

gunicorn app:app -b 127.0.0.1:8000

如何正确设置Flask服务器?

1 个答案:

答案 0 :(得分:1)

您需要将Socket.IO配置添加到nginx。有关详细信息,请参阅https://flask-socketio.readthedocs.io/en/latest/#using-nginx-as-a-websocket-reverse-proxy,但以下是该链接的示例:

server {
    listen 80;
    server_name _;

    location / {
        include proxy_params;
        proxy_pass http://127.0.0.1:5000;
    }

    location /socket.io {
        include proxy_params;
        proxy_http_version 1.1;
        proxy_buffering off;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_pass http://127.0.0.1:5000/socket.io;
    }
}