[英]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.我在 Flask 中使用了 python-socketio,并且想启动Thread
实例并在信号到来时从它发出信号。 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: 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所以对我有用的是在 Flask + python-socketio 中切换到线程模式,如下所述: https ://python-socketio.readthedocs.io/en/latest/server.html#standard-threads
I was using eventlet
before and that caused the problem.我之前使用过eventlet
,这导致了问题。
Using eventlet is possible, but threads must be non-blocking and thus said, standard Threads are useless here.使用 eventlet 是可能的,但线程必须是非阻塞的,因此说,标准线程在这里是无用的。
Instead to create thread one has to use socketio.Server
method start_background_task
which takes function as an argument.要创建线程,必须使用socketio.Server
方法start_background_task
,它将函数作为参数。
Also inside the threaded task, use eventlet.sleep()
instead of the time.sleep()
method.同样在线程任务中,使用eventlet.sleep()
而不是eventlet.sleep()
time.sleep()
方法。
But event that may not work without some hacks and use of monkey_patch
coming with eventlet
.但是,如果没有一些技巧和使用monkey_patch
附带的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.但是如果仍然存在问题,在monkey_patch
之前的导入部分中添加空的eventlet.sleep()
就可以解决问题。 Found it somewhere on the web in a discussion.在讨论中在网络上的某个地方找到了它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.