2

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

Method outside of the context:

@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'

I also tried:

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

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

The method update_client will be called from a thread.

On the Client side:

$(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);
});

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.

There is an example in the documentation:

@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?

Edit:

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

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

manage.py

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

Flask-SocketIO==2.6

eventlet==0.19.0

N. Mauchle
  • 494
  • 1
  • 7
  • 20

1 Answers1

0

I found a solution.

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

python manage.py run

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

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

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

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

N. Mauchle
  • 494
  • 1
  • 7
  • 20