从客户端断开socketio

问题描述 投票:0回答:1

我正在尝试构建一个启动/停止图表显示的工具。在客户端它正确显示图表,但是当我单击停止按钮时,服务器端函数 def start_chart() 不会停止运行。我尝试设置一个全局变量 stop_flag 来打破循环,但它没有自我更新。我以前没有使用过烧瓶或插座,所以无法提出解决方案。任何帮助将不胜感激。

app.py

@socketio.on('start_chart')
def start_chart():
    chart_data = []
    stop_flag = False
    last_emitted_index = 0  # Keep track of the last emitted data index

    for i, row in data.iterrows():
        if stop_flag:
            break
        timestamp = row['timestamp']
        datapoint = row['datapoint']
        if timestamp == 0:
            continue  # Skip zero timestamp
        chart_data.append({'timestamp': timestamp, 'datapoint': datapoint})
        if i > last_emitted_index:
            emit('update_chart', {'chart_data': chart_data})
            last_emitted_index = i
        socketio.sleep(1)  # Emit new data every second
        
    print("Loop Ended")

@socketio.on('stop_chart')
def stop_chart():
    emit('stop_chart') 
    global stop_flag
    stop_flag = True

index.html

<body>
    <button id="start-btn" onclick="startChart()">Start</button>
    <button id="stop-btn" onclick="stopChart()">Stop</button>
</body>
<script>
// Start the chart
    function startChart() {
        if (!isChartRunning) {
            isChartRunning = true;
            socket.emit('start_chart');
        }
    }

    // Stop the chart
    function stopChart() {
        isChartRunning = false;
        socket.emit('stop_chart');
    }
</script>
python flask socket.io flask-socketio
1个回答
0
投票

函数 start_chat() 中的变量 stop_flag 不是全局变量,将“global stop_flag”放在“stop_flag = False”之前。

© www.soinside.com 2019 - 2024. All rights reserved.