Flask-SocketIO: Emitting from background thread to the second room blocks the first room
Hello dear Miguel
changes in app.py
i = 0
def background_thread():
"""Example of how to send server generated events to clients."""
#count = 0
global i
while True:
socketio.sleep(10)
#count += 1
socketio.emit('my_response',
{'data': 'Server generated event', 'count': count},
namespace='/test' , room = i)
@socketio.on('connect', namespace='/test')
def test_connect():
global thread
global i
i += 1
join_room(i)
with thread_lock:
if thread is None:
thread = socketio.start_background_task(target=background_thread)
emit('my_response', {'data': 'Connected', 'count': 0})
These are the only changes in you example code , client A connects and automatically gets his room and the background thread keeps emitting to his room , when B connects it get the thread event but it blocks thread generated event to A and so on … C blocks B …
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Comments: 19 (8 by maintainers)
If this is a robust application that you are building (i.e. not a quick test) you will need to keep track of those threads and stop them when their respective clients disconnect. The return value from the
start_background_taskfunction is the thread object, which you can store in a dictionary or similar data structure.If you want to learn more about how green threads work, I recommend an excellent talk by Dave Beazley titled “concurrency from the ground up”. It’s on youtube.
No, you seem to be trying to do something that this library doesn’t do. Emits go to clients, not to other parts of the server. If you need your threads to pass data around, you need to use threading synchronization primitives and possibly also global variables.
I have learnt python from Dave Beazley’s vidoe courses . He taught me not only how to code but also what is like to be a coding expert .
Thank you for the recommendation
Thank you ! at long last i get the solution , now it works fine
It is great to join newly connected client to his individual room on-fly and direct a separate background thread strictly to him simultaneously with other events .
I wonder how does this work , both threading and
eventletdo their asynchronous jobs , say , Green threads , i want to know how i can track theirzeroesandones, i mean monitoring and controlling them up to their roots …Any way , thank you very much for solving world’s problems
Do it like this: