Flask iperf3 Server: Real-time Output Streaming
{ "title": "iperf3 Server", "description": "Real-time streaming of iperf3 server output", "keywords": "iperf3, server, streaming, real-time, output" }
import subprocess from flask import Flask, render_template, request, jsonify, Response, stream_with_context
app = Flask(name, template_folder='templates') process = None output_list = [] stream_list = []
@app.route('/') def index(): return render_template('index.html')
@app.route('/start', methods=['POST']) def start(): global process, output_list, stream_list if process: return jsonify({'message': 'Command already running.'})
process = subprocess.Popen(['iperf3', '-s', '-p', '1111'], stdout=subprocess.PIPE, universal_newlines=True)
def stream():
while process and process.poll() is None:
output = process.stdout.readline().strip()
stream_list.append(output)
yield output + '\n'
return Response(stream_with_context(stream()), mimetype='text/plain')
@app.route('/stream') def stream(): global stream_list if stream_list: def generate(): while stream_list: output = stream_list.pop(0) yield output + '\n' return Response(generate(), mimetype='text/event-stream') else: def empty_stream(): yield 'data: \n\n' return Response(empty_stream(), mimetype='text/event-stream')
@app.route('/stop', methods=['POST']) def stop(): global process, output_list, stream_list if process: process.terminate() process = None output_list = [] stream_list = [] return jsonify({'message': 'Command stopped.'}) else: return jsonify({'message': 'No command running.'})
if name == 'main': app.run()
原文地址: https://www.cveoy.top/t/topic/qx8v 著作权归作者所有。请勿转载和采集!