emit() in loop not sending until loop completion when using eventlet
See original GitHub issueI am working on a simple Flask-SocketIO app that streams data data from a server to the users browser in real time. I am stuck though when trying to use emit() in a loop. The behavior I am getting is that emit() does not actually send any data to the client until the entire loop is finished executing.
Here is some example code that shows the same behavior:
@socketio.on('rcv_args_and_run')
def rcv_args_and_run(args):
numy = 1
while numy < 10:
socketio.emit('results','Message from server #' + str(numy))
print('Message from server #' + str(numy))
time.sleep(5)
numy += 1
disconnect()
I am developing this locally using the flask/flask-socketio dev server and when I do not have the eventlet package installed it performs as expected, I believe because it then uses long polling. When I install eventlet though I start to get this behavior.
I have looked around at similar issues but can’t exactly tell if the behavior I am getting would be solved by the steps you recommended they take.
Issue Analytics
- State:
- Created 7 years ago
- Comments:9 (4 by maintainers)
Try switching
time.sleep(5)
tosocketio.sleep(5)
. The sleep function from the Python library is not compatible with eventlet, you have to either monkey patch it, or use eventlet’s own sleep function. Thesocketio.sleep()
function routes the sleep call to the proper place, depending on what asynchronous framework you are using.Hum…it seems like the monkey patching might have worked! I used this document and it does seem to explain things very well: http://eventlet.net/doc/patching.html.
I guess the idea solution would have been to wrote my code from the perspective of using Eventlet from the beginning and to only use eventlet/flask socket io approved io methods.
I need to learn more about Evenlet and asynchronous programming with Python in the future!
I am still confused as to good debugging techniques to identify what line of code is actually causing the blocking in the future.
Regardless, thanks so much for you quick responses! Do you have a donation link or something to help support Flask-socketio?