5

我想向套接字客户端发出延迟消息。例如,当一个新的客户端连接时,应该向客户端发出“检查开始”消息,并且在特定秒后应该发出来自线程的另一条消息。

@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')

是否可以从线程发射?

4

1 回答 1

4

The problem is that the thread does not have the context to know what user to address the message to.

You can pass request.namespace to the thread as an argument, and then send the message with it. Example:

@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')
于 2015-01-05T17:38:29.020 回答