异常信息:
源代码:
# -*- coding:UTF-8 -*-
"""
@ProjectName : Coded
@FileName : app
@Description: flask 推送消息给客户端
@Time : 2022/12/3 15:19
@Author : Qredsun
"""
from flask import Flask, render_template
from flask_socketio import SocketIO
from threading import Lock
import random
async_mode = None
# async_mode = 'threading'
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)
thread = None
thread_lock = Lock()
@app.route('/')
def index():
return render_template('index.html', async_mode=socketio.async_mode)
@socketio.on('connect', namespace='/test_conn')
def test_connect():
global thread
with thread_lock:
if thread is None:
thread = socketio.start_background_task(target=background_thread)
def background_thread():
while True:
socketio.sleep(2)
t = random.randint(1, 100)
socketio.emit('server_response', {'data': t}, namespace='/test_conn')
@socketio.on('disconnect', namespace='/chat')
def test_disconnect():
print('Client disconnected')
if __name__ == '__main__':
# socketio.run(app, debug=True)
app.run(debug=True) # , use_reloader=False
问题分析:
RuntimeError: You need to use the eventlet server. See the Deployment section of the documentation for more information.
从异常信息中看是要求使用 eventlet server.
,而我的代码中没有指定async_mode
,即flask默认使用了eventlet
。
如果使用socketio的run,程序运行是没有问题的。查看源代码,发现在socketio初始化时,设置async_mode = 'threading'
解决方法:
-
方法一
指定async_mode
为threading
即可 -
方法二
使用socketio的run方法