Issue
I want to stream a video from a flask server to a webpage. For testing purpose I only send text strings. The problem is that the client only receives the packages at the end. I have to wait 30 seconds and then I get all the messages. When I am using a endless loop to stream then the client never receives a message. This is my server code:
from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO, emit, send
from flask_cors import CORS
import cv2
import base64
import time
app = Flask(__name__)
app.config['SECRET_KEY'] = 'justasecretkeythatishouldputhere'
socketio = SocketIO(app, cors_allowed_origins="http://localhost:3000", logger=True, engineio_logger=True)
CORS(app)
@socketio.on('connect')
def on_connect(auth):
print("CONNECTED")
@socketio.on("live")
def live(test):
cap = cv2.VideoCapture(0)
counter = 0
for _ in range(30):
counter += 1
ret,frame = cap.read()
retval, buffer = cv2.imencode('.jpg', frame)
send(f"Hi, {counter}")
time.sleep(1)
if __name__ == '__main__':
socketio.run(app)
And this is my client code:
import {useEffect, useState} from 'react'
import logo from './logo.svg';
import './App.css';
import { io } from "socket.io-client";
function App() {
const [test, setText] = useState("test")
useEffect(()=>{
const socket = io("http://localhost:5000");
console.log(socket)
socket.on('message', function (data) {
console.log(data)
setText(data)
});
socket.emit('live', "data");
},[])
return (
<div className="App">
{test}
</div>
);
}
export default App;
Solution
Are you using ASGI web server to host this app, probably eventlet?
Your main loop occupies resources for the whole time and socketio
doesn't have time to send data through a websocket - that's why you receive all the messages at the end. Simple time.sleep
don't release it.
Try replacing time.sleep(1)
with socketio.sleep(0)
.
Answered By - softartisan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.