import subprocess
from flask import Flask, render_template, request, jsonify, Response, stream_with_context

app = Flask(__name__, template_folder='D:\temp\dddd\')
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 + '
'

    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 + '
'
        return Response(generate(), mimetype='text/event-stream')
    else:
        def empty_stream():
            yield 'data: 

'
        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()

This Flask application creates a simple server that streams IPerf3 output in real-time, enabling you to monitor network bandwidth using a web interface.

Key Features:

  • Real-time IPerf3 Output: The app continuously captures and streams IPerf3 output to the web client.
  • Web Interface: A basic HTML page provides buttons to start and stop the IPerf3 process, along with a display area to show the streamed output.
  • EventSource API: The server utilizes the EventSource API to push IPerf3 data to the client in a continuous stream.

Implementation Details:

  1. Running IPerf3: The start() route initializes an IPerf3 server process using subprocess.Popen(). The output of the process is captured using stdout=subprocess.PIPE.
  2. Streaming Output: The stream() route handles the streaming of data. It uses a generator function to continuously read lines from the IPerf3 output and yield them to the client. The Response object is configured with mimetype='text/event-stream' for EventSource compatibility.
  3. Client-Side Logic: The index.html file contains JavaScript code to connect to the server's /stream endpoint using EventSource and display the received output in a div element.
  4. Start/Stop Controls: The start() and stop() routes handle starting and stopping the IPerf3 process, respectively.

To run this app:

  1. Ensure you have Flask and IPerf3 installed: pip install flask iperf3
  2. Save the Python code as app.py and the HTML code as index.html in the same directory.
  3. Run the server: python app.py
  4. Open http://127.0.0.1:5000/ in your web browser.

Note: This app assumes you have IPerf3 installed on the same machine where you are running the Flask server.

This example demonstrates a basic use case for streaming data from a subprocess using Flask and EventSource. You can expand this to incorporate more features, like customizable IPerf3 parameters, data visualization, and persistent logging.

<!DOCTYPE html>
<html>
<head>
    <title>IPerf3 Streaming</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
        $(document).ready(function() {
            var eventSource = new EventSource("/stream");

            eventSource.onmessage = function(event) {
                var data = event.data;
                if (data) {
                    $('#output').append(data + '<br>');
                }
            };

            $('#startButton').click(function() {
                $.ajax({
                    url: '/start',
                    type: 'POST',
                    success: function(response) {
                        console.log(response.message);
                    }
                });
            });

            $('#stopButton').click(function() {
                $.ajax({
                    url: '/stop',
                    type: 'POST',
                    success: function(response) {
                        console.log(response.message);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <h1>IPerf3 Streaming</h1>
    <button id="startButton">Start</button>
    <button id="stopButton">Stop</button>
    <div id="output"></div>
</body>
</html>
Flask IPerf3 Streaming Server: Real-Time Network Bandwidth Monitoring

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

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