As noted by @MatsLindh in the comments, you should rather use a more suitable protocol - such as WebSockets - than HTTP
for such a task. FastAPI/Starlette supports sending and receiving data on a websocket
(see the documentation here and here). Below is an example of using websockets
to send video frames from a client to a server (assuming this is your task from your comment on 30fps
- however, the same appproach could be applied to sending other types of data). OpenCV
is used to capture the frames and websockets
library is used to connect to the WebSocket server.
server.py
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
import cv2
import numpy as np
app = FastAPI()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
# listen for connections
await websocket.accept()
#count = 1
try:
while True:
contents = await websocket.receive_bytes()
arr = np.frombuffer(contents, np.uint8)
frame = cv2.imdecode(arr, cv2.IMREAD_UNCHANGED)
cv2.imshow('frame', frame)
cv2.waitKey(1)
#cv2.imwrite("frame%d.png" % count, frame)
#count += 1
except WebSocketDisconnect:
cv2.destroyWindow("frame")
print("Client disconnected")
client.py
import websockets
import asyncio
import cv2
camera = cv2.VideoCapture(0, cv2.CAP_DSHOW)
async def main():
# Connect to the server
async with websockets.connect('ws://localhost:8000/ws') as ws:
while True:
success, frame = camera.read()
if not success:
break
else:
ret, buffer = cv2.imencode('.png', frame)
await ws.send(buffer.tobytes())
# Start the connection
asyncio.run(main())