I'm building a API server that can stream video to clients. Is there any way to disconnect specific tcp connection with client's socket ip and port information?
What I wanna do is :
- If there's an request to turn off a streaming video, my fastAPI server can disconnect the related tcp connection(HTTP connection).
- When a client make the request, it will send information of its socket ip address and port.
What I confused with is: How can I access the client socket instance that was automatically made by Uvicorn (because I'm building an API with fastAPI)
import uvicorn
from fastapi import FastAPI
app = FastAPI()
def get_video():
...
current_frame_bytes = # making bytes data per frame
...
yield b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + current_frame_bytes + b'\r\n'
@app.get("/streaming_video")
async def streaming_video():
return StreamingResponse(get_video(),media_type="multipart/x-mixed-replace; boundary; boundary=frame")
In Summary(a simple example)
my fastapi server socket : 127.0.0.1:8000
there are 3 clients are established with my server
127.0.0.1:100 (client 1) 127.0.0.2:200 (client 2) 127.0.0.3:300 (client 3)
if there is a request to disconnect client2(127.0.0.1:200), I wanna make my server be able to disconnect the specific tcp connection by using the client socket's port info.
I wanna use shutdown(), close() method to disconnect and close a socket. But, I don't know how to access the instance of a connected client socket made by fastAPI. So, I tried the below code
import socket
...
@app.POST('/stop_streaming/{port}')
async def stop_streaming(port:int):
client_socket = socket.socket()
ADDR = '' # client_host ip
PORT = port # client provide their port info when making a request
client_socket.bind((ADDR,PORT))
client_socket.shutdown()
client_socekt.close()