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:

  1. start Route:

    In the start route, we append each output line from the iPerf3 command to both the stream_list and a new list called output_list. The stream_list is used for streaming the output to the client, while output_list will 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')
    
  2. stream Route:

    In the stream route, we return the contents of the output_list as an event stream. We then clear the output_list to 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')
    
  3. Frontend JavaScript:

    In the frontend page, we use JavaScript to listen for messages from the /stream route. 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.

Flask App: Display iPerf3 Logs in Real-Time

原文地址: https://www.cveoy.top/t/topic/qx8L 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录