socketio的start_background_task函数用于新建一个线程,处理业务,在线程中在请求上下文中调用收发功能函数

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)

def background_thread():
    """Example of how to send server generated events to clients."""
    count = 0
    while True:
        socketio.sleep(10)
        count += 1
        socketio.emit('my_response',
                      {'data': 'Server generated event', 'count': count},
                      namespace='/test')



@socketio.on('connect', namespace='/test')
def test_connect():
    global thread
    if thread is None:
        thread = socketio.start_background_task(target=background_thread)
    emit('my_response', {'data': 'Connected', 'count': 0})

 

 

来自flask-socketio官方github示例代码

https://github.com/miguelgrinberg/Flask-SocketIO/blob/master/example/app.py

包括了基本的函数调用情况,极具实用价值

posted on 2016-09-07 20:34  夕照_Joy  阅读(6885)  评论(0编辑  收藏  举报