タイトル通りです。
Flask+Pythonを使って、UDPのデータを受信したらvideoタグのソースを切り替えたいですが、以下の問題が発生しています。

・動画が切り替わらない時がある。
・UDPの受信処理が始まると、リロードし直せない

  • app.py

    # -*- coding: utf-8 -*-
    from flask import *
    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler
    from socket import socket, AF_INET, SOCK_DGRAM
    from time import sleep
    # from DBclass import FaceClassification
    from DBadapter import DBadapter
    import os
    import re
    
    app = Flask(__name__)
    # app = Flask(__name__, static_folder='video')
    app.config.from_object(__name__)
    count = 0
    # adapter = DBadapter()
    ad = DBadapter()
    # @app.route("/", methods=["POST"])
    
    
    @app.route("/cm", methods=["GET", "POST"])
    def cm_page():
        return render_template('cm.html')
    @app.route('/pipe')
    def pipe():
        print("PIPE!!!")
        # sockSend = socket(AF_INET,SOCK_DGRAM)
        sockRecv = socket(AF_INET,SOCK_DGRAM)
        sockRecv.bind(("192.168.2.59",7777))
        buffSize = 100
        # sendIp = "localhost"
        # sendPort = 1111
    
        if request.environ.get('wsgi.websocket'):
            ws = request.environ['wsgi.websocket']
    
            while True:
                recvData, addr = sockRecv.recvfrom(buffSize)
                sleep(0.1)
                if len(recvData) > 0 :
                    recvData= recvData.decode('utf-8')
                    print("recv:" +str(recvData))
                    if str(recvData) == "Fue" :
                        ws.send("/static/video/1.webm")
                    elif str(recvData) == "Mue" :
                        ws.send("/static/video/2.webm")
                    elif str(recvData) == "Fsita" :
                        ws.send("/static/video/3.webm")
                    elif str(recvData) == "Msita" :
                        ws.send("/static/video/4.webm")
                    else :
                        print("cant read msg :" + str(recvData))
    
    
    
    if __name__ == "__main__":
        # ad = new DBadapter()
        count = 0
        app.debug= True
        print (app.url_map)
        server = pywsgi.WSGIServer(("localhost", 8888), app, handler_class=WebSocketHandler)
        server.serve_forever()
        # app.run(debug=True, host='0.0.0.0', port=8888, threaded=True)
        # print("ss")
        # age0s= list(age0),
    
  • app.py

<!doctype html>
<html lang=en>
<head>
<title>the new code - FullScreen HTML5 Video In Pure CSS</title>
<link href="//cloud.webtype.com/css/094b1fa9-6433-4dce-966d-931c186185d8.css" rel="stylesheet" type="text/css" />
<style>
body { margin: 0; background: #000;}
video { 
position: fixed;
top: 50%;
left: 50%;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
z-index: -100;
-moz-transform: translateX(-50%) translateY(-50%);
-ms-transform: translateX(-50%) translateY(-50%);
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
background: url('') no-repeat; background-size: cover;  -webkit-transition: 1s opacity; transition: 1s opacity; }
/* background: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/polina.jpg') no-repeat; background-size: cover;  -webkit-transition: 1s opacity; transition: 1s opacity; } */
div { font-family: Agenda-Light, Agenda Light, Agenda, Arial Narrow, sans-serif;   
font-weight: 100; background: rgba(0, 0, 0, 0.8); color: white; padding: 2rem; width: 33%; margin: 2rem; float: right; font-size: 1.2rem; }
h1 { font-size: 2rem; text-transform: uppercase; margin-top: 0; letter-spacing: .3rem; }
a { display: inline-block; color: #fff; text-decoration: none; background: rgba(0,0,0,0.5); 
padding: .5rem; -webkit-transition: .6s background; transition: .0s background; }
a:hover { background: rgba(0,0,0,0.9); }
.stopfade { opacity: .5; }
#polina button { 
  display: block;
  width: 80%;
  padding: .4rem;
  border: none; 
  margin: 1rem auto; 
  font-size: 1.3rem;
  background: rgba(0, 0, 0, 0);
  color: #fff;
  border-radius: 3px; 
  cursor: pointer;
  -webkit-transition: .3s background;
  transition: .3s background;
}
#polina button:hover { 
   background: rgba(255, 0, 0, 0.5);
}

@media screen and (max-width: 500px) { 
/* @media screen and (max-width: 50px) {  */
  div{width:70%;} 
}
@media all and (max-device-width: 800px) {
  /* body { background: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/polina.jpg") #000 no-repeat center center fixed; background-size: cover; } */
  body { background: url("") #000 no-repeat center center fixed; background-size: cover; }
  #bgvid, #polina button { display: none; }
  div{width:70%;} 
}
</style>
<meta charset=utf-8>
</head>
<body>
  <video autoplay preload="auto" id="bgvid" >
      <!-- <video poster="" id="bgvid" playsinline autoplay muted loop> -->
  <!-- 
- Video needs to be muted, since Chrome 66+ will not autoplay video with sound.
WCAG general accessibility recommendation is that media such as background video play through only once. Loop turned on for the purposes of illustration; if removed, the end of the video will fade in the same way created by pressing the "Pause" button  -->
<!-- <source src="video/sample.mp4" type="video/webm"> -->

<!-- <source src="http://thenewcode.com/assets/videos/polina.webm" type="video/webm"> -->
<!-- <source src="http://thenewcode.com/assets/videos/polina.mp4" type="video/mp4"> -->
   <!-- <source src="/static/video/A.webm" type="video/webm"> -->
    <!-- <source src="http://192.168.2.59:8888/static/video/sample.mp4" type="video/mp4">  -->
    <!-- <source src="/static/video/B.webm" type="video/webm"> -->
      <!-- <source id="backcm" src="/static/video/A.webm" type="video/webm"> -->
        <!-- <source id="backcm"  type="video/webm"> -->
    <!-- <source src="http://192.168.2.59:8888/static/video/sample.mp4" type="video/mp4"> -->
<!-- <source src="video/sample.mp4" type="video/mp4"> --> 

</video>
<div id="polina">

<h1>たいとる</h1>
ここに文字


<!-- <p>filmed by Alexander Wagner 2011
<p><a href="http://thenewcode.com/777/Cre"/static/video/B.webm"ate-Fullscreen-HTML5-Page-Background-Video">original article</a>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur porta dictum turpis, eu mollis justo gravida ac. Proin non eros blandit, rutrum est a, cursus quam. Nam ultricies, velit ac suscipit vehicula, turpis eros sollicitudin lacus, at convallis mauris magna non justo. Etiam et suscipit elit. Morbi eu ornare nulla, sit amet ornare est. Sed vehicula ipsum a mattis dapibus. Etiam volutpat vel enim at auctor.</p>
<p>Aenean pharetra convallis pellentesque. Vestibulum et metus lectus. Nunc consectetur, ipsum in viverra eleifend, erat erat ultricies felis, at ultricies mi massa eu ligula. Suspendisse in justo dapibus metus sollicitudin ultrices id sed nisl.</p>
<button>Pause</button> -->
</div>




<!-- <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script type="text/javascript">

</script> -->



<script>
var endflag = true;
var ws = new WebSocket("ws://localhost:8888/pipe");

var vid = document.getElementById("bgvid");
ws.onmessage = function(e) {
  // var vid = document.getElementById("bgvid");
  // document.getElementById("text-field").innerHTML = e.data;
  console.log(e.data)
  vid.src = e.data;
  endflag = false;
  vid.load();
   vid.play();
  // p.catch(function(e) {
  //     console.log(e.data)
  // });
  // vid.
}

vid.addEventListener("ended", function(){
  // var vid2 = document.getElementById("bgvid");
  vid.src = ""
  console.log("end movie");
  // vid2.stop();
  endflag = true;
}, false);

// var pauseButton = document.querySelector("#polina button");

// if (window.matchMedia('(prefers-reduced-motion)').matches) {
//     vid.removeAttribute("autoplay");
//     vid.pause();
//     pauseButton.innerHTML = "Paused";
// }

// function vidFade() {
//   vid.classList.add("stopfade");
// }

// vid.addEventListener('ended', function()
// {
// // only functional if "loop" is removed 
// vid.pause();
// // to capture IE10
// vidFade();
// }); polina


// pauseButton.addEventListener("click", function() {
//   vid.classList.toggle("stopfade");
//   if (vid.paused) {
//     vid.play();
//     pauseButton.innerHTML = "Pause";
//   } else {
//     vid.pause();
//     pauseButton.innerHTML = "Paused";
//   }
// })



</script>

</body>
</html>