我想向套接字客户端发出延迟消息。例如,当新客户端连接时,"检查开始"应该将消息发送到客户端,并在一定时间后发出来自线程的另一条消息。
@socket.on('doSomething', namespace='/test')
def onDoSomething(data):
t = threading.Timer(4, checkSomeResources)
t.start()
emit('doingSomething', 'checking is started')
def checkSomeResources()
# ...
# some work which takes several seconds comes here
# ...
emit('doingSomething', 'checking is done')
但由于上下文问题,代码无效。我得到了
RuntimeError('working outside of request context')
是否可以通过线程发光?
答案 0 :(得分:4)
问题在于线程没有上下文来知道要将消息发送到哪个用户。
您可以将request.namespace
作为参数传递给线程,然后使用它发送消息。例如:
@socket.on('doSomething', namespace='/test')
def onDoSomething(data):
t = threading.Timer(4, checkSomeResources, request.namespace)
t.start()
emit('doingSomething', 'checking is started')
def checkSomeResources(namespace)
# ...
# some work which takes several seconds comes here
# ...
namespace.emit('doingSomething', 'checking is done')