本文介绍了从Flask SocketIO事件上下文向外部发送事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试从SocketIO事件上下文向外部发送套接字消息时,该消息未到达客户端.

When I try to send a socket message outside from the SocketIO event context, the message does not arrive at the client.

上下文之外的方法:

@main.route('/import/event', methods=['POST'])
def update_client():
   from .. import socketio
   userid = request.json['userid']
   data = request.json
   current_app.logger.info("New data: {}".format(data))
   current_app.logger.info("Userid: {}".format(userid))
   socketio.emit('import', data, namespace='/events', room=userid)
   return 'ok'

我也尝试过:

    with current_app.app_context():
        socketio.emit('import', data, namespace='/events', room=userid)

在SocketIO上下文"on.connect"上

On the SocketIO Context 'on.connect'

@socketio.on('connect', namespace='/events')
def events_connect():
    current_app.logger.info("CONNECT {}".format(request.namespace))
    userid = request.sid
    current_app.clients[userid] = request.namespace

方法update_client将从线程中调用.

The method update_client will be called from a thread.

在客户端:

$(document).ready(function(){
  var socket = io.connect('http://' + document.domain + ':' + location.port +'/events');
  var userid;

socket.on('connect', function() {
    console.log("on connect");
});

socket.on('import', function (event) {
  console.log("On import" +event);
});

当我在 @ socketio.on('connect')方法中调用 emit('import','test')时,消息到达客户端,然后日志消息已打印.

When I call the emit('import', 'test') in the @socketio.on('connect') method the messages arrives at the client and the log message is printed.

文档中有一个示例:

@app.route('/ping')
def ping():
    socketio.emit('ping event', {'data': 42}, namespace='/chat')

我错过了什么吗?为什么消息没有到达客户端?

Do I miss something or why does the message not arrive at the client?

socketio是在 app/__ init __.py 函数

The socketio is created in the app/__init__.py function

socketio = SocketIO()
create_app():
   app = Flask(__name__)
   socketio.init_app(app)

manage.py

manage.py

from app import socketio
if __name__ == '__main__':
    socketio.run(app)

Flask-SocketIO == 2.6

Flask-SocketIO==2.6

eventlet == 0.19.0

eventlet==0.19.0

推荐答案

我找到了解决方案.

当我与flask内部服务器一起运行该应用程序时,客户端不会接收到消息.

When I run the application with the flask internal server, the messages are not received by the client.

python manage.py run

但是当我用gunicorn运行服务器时,所有的工作都像灵符.

But when I run the server with gunicorn all works like a charm.

所以这里的解决方案是使用带有eventlet的Gunicorn.

So the solution here is to use the gunicorn with eventlet.

gunicorn --worker-class eventlet -w 1 manage:app

我将Flask 0.11与Flask-Migrate 2.0一起使用.也许我错过了一些东西,因为Flask 0.11有一个新的启动命令.

I use Flask 0.11 with Flask-Migrate 2.0. Perhaps I missed something, since Flask 0.11 has a new startup command.

这篇关于从Flask SocketIO事件上下文向外部发送事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 07:10