使用Flask的承插延伸管从螺纹中发射

2024-10-01 15:28:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我想向套接字客户机发送延迟消息。例如,当一个新的客户机连接时,“checking is started”消息应该发送到该客户机,并且在某一秒之后,应该从某个线程发出另一条消息。在

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

但是由于上下文问题,代码不能工作。我明白了

^{pr2}$

有可能从一根线发射吗?在


Tags: test消息客户机isondefsocket线程
1条回答
网友
1楼 · 发布于 2024-10-01 15:28:50

问题是线程没有上下文来知道要将消息发送给哪个用户。在

您可以将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')

相关问题 更多 >

    热门问题