I run the Flask server on my local machine and use it to extract data from the serial port and display it in real time on the web page using Flask-socketio. I followed suit here and see interesting behavior. I was able to reproduce the results of the example, but when I change the background_thread function to enable reading and analysis of data from the serial port, it looks like the socket is blocking from sending data. My code sets the socket correctly and opens the connection, and can even correctly generate messages at the beginning of the stream function, but after it gets into time.sleep (5), the emission no longer works. This uses the original thread function, which works (and includes time.sleep ()!):
def background_thread(): """Example of how to send server generated events to clients.""" count = 0 while True: time.sleep(1) count += 1 socketio.emit('my response', {'data': 'Server generated event', 'count': count}, namespace='/test')
Here is a snippet from my code. I use the delay to wait for my serial device to complete the operation before reading it again.
socketio.emit('my response', {'data': 'waiting'}, namespace='/test') print( "waiting...", file=sys.stderr) time.sleep(5) socketio.emit('my response', {'data': 'done sleeping'}, namespace='/test')
In this case, I see a โwaitโ message, but not a โdone sleepโ message or other messages after that. There are no errors, the code works correctly. However, when I press ctrl + c to kill the script, suddenly all the messages that I tried to emit after time.sleep () appear on the browser side. This somehow blocks and buffers all messages, and then flushes them when the script is killed. I also tried to find out if there was a time and a problem:
socketio.emit('my response', {'data': 'waiting'}, namespace='/test') print( "waiting...", file=sys.stderr) socketio.emit('my response', {'data': 'about to sleep'}, namespace='/test') time.sleep(1) socketio.emit('my response', {'data': 'sleep 1'}, namespace='/test') time.sleep(1) socketio.emit('my response', {'data': 'sleep 2'}, namespace='/test') time.sleep(1) socketio.emit('my response', {'data': 'sleep 3'}, namespace='/test') time.sleep(1) socketio.emit('my response', {'data': 'sleep 4'}, namespace='/test') time.sleep(1) socketio.emit('my response', {'data': 'done sleeping'}, namespace='/test')
In this case, I saw the message "sleep 4", but nothing happened after that. Changing the number of sleep announcements has always led to him not issuing anything since his last sleep. To add to the secret, if I completely delete the sleep instructions, I donโt see anything coming from the stream at all.
I am using version 1.4.5 of Flask-socketio and eventlet as an async service. I tried replacing time.sleep () with eventlet.sleep (), but saw the same behavior.