Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run python-socketio in Thread?

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);
});
like image 495
Janusz 'Ivellios' Kamieński Avatar asked May 05 '17 09:05

Janusz 'Ivellios' Kamieński


1 Answers

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.

Another solution

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.

like image 88
Janusz 'Ivellios' Kamieński Avatar answered Sep 24 '22 17:09

Janusz 'Ivellios' Kamieński