Flask App: Display iPerf3 Logs in Real-Time
This Flask application demonstrates how to display iPerf3 logs in real-time on a webpage. It utilizes server-sent events (SSE) to stream the output of the iPerf3 command to the client.
To achieve this, we modify the start and stream routes in the Flask application:
-
startRoute:In the
startroute, we append each output line from the iPerf3 command to both thestream_listand a new list calledoutput_list. Thestream_listis used for streaming the output to the client, whileoutput_listwill be used to store and display the logs on the page.@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() output_list.append(output) # Add output to output_list stream_list.append(output) yield output + '\n' return Response(stream_with_context(stream()), mimetype='text/plain') -
streamRoute:In the
streamroute, we return the contents of theoutput_listas an event stream. We then clear theoutput_listto prevent duplicate log entries.@app.route('/stream') def stream(): global output_list if output_list: def generate(): while output_list: output = output_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') -
Frontend JavaScript:
In the frontend page, we use JavaScript to listen for messages from the
/streamroute. When a message is received, we display it on the page. Here's an example:var eventSource = new EventSource('/stream'); eventSource.onmessage = function(event) { var log = event.data; // Display log on the page };
By implementing these changes, the Flask application will now stream the output of the iPerf3 command in real-time and display it on the webpage.
原文地址: https://www.cveoy.top/t/topic/qx8L 著作权归作者所有。请勿转载和采集!