I have python-socketio used in Flask and want to start Thread
instance and emit signals from it when signal comes. In flask app I have:
import threading
def game(my_sio):
my_sio.emit('log', data = "Game started!")
return
@sio.on('start')
def startGame(sid):
t = threading.Thread(target = game, args = [sio])
t.start()
There's a simple example and it does not work. In server log I get:
engineio:a16afb90de2e44ab8a836498086c88f6: Sending packet MESSAGE data 2["log","Game started!"]
But client never gets it!
Javascript:
socket.on('log', function(a) {
console.log(a);
});
So what worked for me was switching to threading mode in Flask + python-socketio as documented here: https://python-socketio.readthedocs.io/en/latest/server.html#standard-threads
I was using eventlet
before and that caused the problem.
Using eventlet is possible, but threads must be non-blocking and thus said, standard Threads are useless here.
Instead to create thread one has to use socketio.Server
method start_background_task
which takes function as an argument.
Also inside the threaded task, use eventlet.sleep()
instead of the time.sleep()
method.
But event that may not work without some hacks and use of monkey_patch
coming with eventlet
. See more in documentation. But if there are still problems, adding empty eventlet.sleep()
in the import section right before the monkey_patch
will do the trick. Found it somewhere on the web in a discussion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With