use*_*716 7 python websocket flask flask-socketio
我正在尝试创建一个'keepalive'websocket线程,一旦有人连接到页面但每10秒发送一次,就会发出一个错误但是不确定如何绕过它.知道如何使这项工作.一旦'断开'被发送,我将如何杀死这个线程?
谢谢!
@socketio.on('connect', namespace='/endpoint')
def test_connect():
emit('my response', {'data': '<br>Client thinks i\'m connected'})
def background_thread():
"""Example of how to send server generated events to clients."""
count = 0
while True:
time.sleep(10)
count += 1
emit('my response', {'data': 'websocket is keeping alive'}, namespace='/endpoint')
global thread
if thread is None:
thread = Thread(target=background_thread)
thread.start()
Run Code Online (Sandbox Code Playgroud)
您编写后台线程的方式要求它知道客户端是谁,因为您要向其发送直接消息.因此,后台线程需要访问请求上下文.在Flask中,您可以使用copy_current_request_context装饰器在线程中安装当前请求上下文的副本:
@copy_current_request_context
def background_thread():
"""Example of how to send server generated events to clients."""
count = 0
while True:
time.sleep(10)
count += 1
emit('my response', {'data': 'websocket is keeping alive'}, namespace='/endpoint')
Run Code Online (Sandbox Code Playgroud)
几个笔记:
emit调用将位于客户端使用的相同命名空间上.在请求上下文之外广播或发送消息时,需要指定命名空间.要在客户端断开连接时停止线程,可以使用任何多线程机制让线程知道它需要退出.例如,这可以是您在disconnect事件上设置的全局变量.一个不太容易实现的不太好的选择是等待emit客户端离开时使用它来退出线程时引发异常.
| 归档时间: |
|
| 查看次数: |
6428 次 |
| 最近记录: |