python-socketio: Client doesn't receive emits from Thread
Is this package Thread-safe? I have code like:
# in controller.py file
class Controller():
def run_me(self):
self.sio.emit('log', data = "Starting game")
return
def __init__(self, sio):
self.sio = sio
def startThread(self):
t = threading.Thread(target = self.run_me, )
t.start()
return t
# app.py file
sio = socketio.Server(logger=True)
rc = Controller(sio)
@sio.on('ping')
def ping(sid):
sio.emit('pong', data = "PING_PONG")
@sio.on('start')
def startGame(sid):
#sio.emit('log', data = 'Going into thread') # that makes emit in thread working, but without this it gets broken.
rc.startThread()
And in client there’s a simple:
$('#start').click(function(e){
e.preventDefault();
socket.emit('start');
});
socket.on('pong', function(a) {
console.log(a);
});
socket.on('log', function(a) {
console.log(a);
});
When I use PING in client, it logs in cosole PING_PONG. But when I emit start it doesn’t emit log to client. And there’s more: ping stops working too. In my server sio logs, there’s info, that the messages are sent, but client seems not receiving it.
Is it possible, that Thread is somehow breaking the connection?
Also: If I uncomment the line of emit before starting thread, it works fine SOMETIMES. Right now it does not.
I have also tried to have run_me as a separate function and pass sio as an argument:
def run_me(sio):
sio.emit('log', data = "Starting game")
return
class Controller():
def __init__(self, sio):
self.sio = sio
def startThread(self):
t = threading.Thread(target = run_rooms, args = [self.sio])
t.start()
return t
But the result is the same…
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Comments: 17 (7 by maintainers)
@ivellios Is your
sleepfunction the one from Python? That’s not compatible with async frameworks, because it is blocking. Try usingsocketio.sleep()instead, or course, you can use theeventlet.sleep()function directly if you prefer.Here is one: https://github.com/miguelgrinberg/python-socketio/blob/master/examples/wsgi/app.py#L31