import os import signal from time import sleep import threading import numpy as np import requests from flask import Flask, Response import utils app_flask = Flask(__name__) # 全局变量,用于存储最新的帧 latest_frame:np.ndarray = None lock = threading.Lock() is_running = True def update_latest_frame(n_bytes:np.ndarray): global latest_frame latest_frame=n_bytes def generate_mjpeg(): """生成MJPEG格式的视频流""" while is_running: with lock: if latest_frame is None: continue _,latest_frame_bytes = utils.frame_to_img(latest_frame) frame = latest_frame_bytes.tobytes() pass sleep(0.1) yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') @app_flask.route('/video_flow') def video_feed(): """视频流路由""" return Response( generate_mjpeg(), mimetype='multipart/x-mixed-replace; boundary=frame' ) # 添加关闭路由 @app_flask.route('/shutdown', methods=['POST']) def shutdown(): os.kill(os.getpid(), signal.SIGTERM) return 'Server shutting down...' def run(): port=2240 print(f"推流服务启动,访问端口 127.0.0.1:{port}/video_flow") app_flask.run(host='0.0.0.0', port=port, threaded=True) def video_server_run(): thread = threading.Thread(target=run) thread.daemon = True # 设置为守护线程,主线程退出时自动终止 thread.start() def stop(): global is_running is_running = False # 通过HTTP请求关闭Flask服务器 try: response = requests.post('http://localhost:2240/shutdown', timeout=1) print(f"服务器关闭请求发送成功,状态码: {response.status_code}") except requests.exceptions.ConnectionError as e: print(f"无法连接到服务器: {e}") except requests.exceptions.Timeout as e: print(f"关闭请求超时: {e}") except requests.exceptions.RequestException as e: print(f"发送关闭请求时发生错误: {e}") except Exception as e: print(f"关闭服务器时发生未知错误: {e}") if __name__ == '__main__': run()