python# apppyimport subprocessfrom flask import Flask render_template request jsonifyapp = Flask__name__process = Noneapproutedef index return render_templateindexhtmlapproutestart methods=POSTdef
要将iperf3的运行结果实时输出显示到网页上,可以使用Flask的SSE(Server-Sent Events)技术。
首先,需要在HTML模板文件(index.html)中添加一个用于显示iperf3输出的<pre>元素,例如:
<pre id="output"></pre>
然后,需要在JavaScript代码中使用EventSource对象来监听服务器发送的事件,并将数据显示在<pre>元素中。可以将以下代码添加到index.html中:
<script>
var output = document.getElementById('output');
var source = new EventSource('/stream');
source.onmessage = function(event) {
output.innerHTML += event.data + '\n';
output.scrollTop = output.scrollHeight;
};
</script>
接下来,在app.py中添加一个新的路由/stream,用于实时发送iperf3的输出数据给客户端。修改start()函数,将iperf3的输出数据发送到客户端:
import time
@app.route('/start', methods=['POST'])
def start():
global process
if process:
return jsonify({'message': 'Command already running.'})
process = subprocess.Popen(['iperf3', '-s', '-p', '1111'], stdout=subprocess.PIPE, universal_newlines=True)
def generate_output():
while process and process.poll() is None:
output = process.stdout.readline().strip()
yield "data: {}\n\n".format(output)
time.sleep(0.1)
return app.response_class(generate_output(), mimetype='text/event-stream')
修改stop()函数,确保在停止iperf3进程时,关闭SSE连接:
@app.route('/stop', methods=['POST'])
def stop():
global process
if process:
process.terminate()
process = None
return jsonify({'message': 'Command stopped.'})
else:
return jsonify({'message': 'No command running.'})
最后,运行应用程序,打开浏览器访问网页,即可实时显示iperf3的运行结果
原文地址: http://www.cveoy.top/t/topic/iRLB 著作权归作者所有。请勿转载和采集!