python - Flask websocket有延迟
问题描述
我有一个简单的 Flask websocket 实现。我会尽可能详细地解释这一点。
代表问题的python代码:
from flask import Flask, render_template, send_file, redirect, request
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from flask_socketio import SocketIO, emit
....
app = Flask(__name__)
socketio = SocketIO(app, async_mode = 'gevent')
def update_index():
global client_1
while True:
t = datetime.datetime.utcnow().strftime("%H-%M-%S")
print ('time: ' + t)
data = {
'input_15' : 'btn_gray',
'input_16' : 'btn_gray',
'time' : t
}
socketio.emit('update_index', data, namespace='/index')
time.sleep(1)
@app.route('/')
@app.route('/index')
def index():
names = [
['input_1_name'],
['input_2_name'],
['input_3_name'],
['input_4_name'],
['input_5_name'],
['input_6_name'],
['input_7_name'],
['input_8_name'],
['input_9_name'],
['input_10_name'],
['input_11_name'],
['input_12_name'],
['input_13_name'],
['input_14_name'],
['input_15_name'],
['input_16_name']
]
location = 'client_name'
return render_template('index.html', names=names, location=location)
def run_GUI():
app.config['SECRET_KEY'] = 'Admin'
socketio.run(app, host='192.168.0.59', port=80)
if __name__ == '__main__':
t1 = threading.Thread(name='process 1', target=run_GUI)
t2 = threading.Thread(name='process 2', target=update_index)
t1.start()
t1.start()
index.html(文件的脚本部分)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.1.3/socket.io.js" ></script>
<script type="text/javascript">
$(document).ready(function(){
var namespace = '/index';
var socket = io(location.protocol + '//' + document.domain + ':' + location.port + namespace);
socket.on('update_index', function(msg) {
$('#log').append('<p>Received: ' + msg.time + '</p>');
$('#btn15').attr('class', msg.input_15);
$('#btn16').attr('class', msg.input_16);
});
});
虽然这可行,但问题来自延迟。当这个程序运行时,我希望服务器会每隔一秒启动一次数据推送并刷新 html 页面(即按钮类,或附加 tmestamp),但事实并非如此。出于某种原因,我每 5 秒刷新一次,同时发送所有数据(准确地说:我得到相同的刷新 5 个时间戳)。使用 print 语句,我可以看到服务器按预期工作。这看起来有一些缓冲。我不知道如何解释这一点,但独自一人如何重新爱上它。
附加信息:服务器在 Ubuntu 18.04.3 LTS 上运行,我已经安装了 eventlet、gevent 和 gevent-websocket
Python版本:3.6.9
解决方案
推荐阅读
- python - 使用 pandas 时如何删除列表中的 nan?
- arrays - Azure 数据工厂 - 展平 JSON 时跳过具有空集合引用的行
- php - 将 post_id 作为我下一个数组的键
- ios - WebKit 上令人困惑的崩溃
- ramda.js - Ramda - 使用 applySpec 访问地图的元素
- apache - Apache RewriteRule 不适用
- java - MultipleBagFetchException:不能同时获取多个包
- elasticsearch - 即使将单个标识符作为查询的一部分传递,NativeSearchQuery 也会返回所有结果
- php - 无法在 laravel 8 中显示模态形式
- python - 张量流模型和转换后的 tflite 之间的精度下降