仅收到部分流媒体 MP4

问题描述 投票:0回答:1

我需要通过Python中的套接字通过互联网直播视频。由于单独的帧速度很慢,我尝试发送 mp4 文件(简化代码):

# server (sender)
import socket

if __name__ == '__main__':
    with open('vid.mp4', 'rb') as f:
        data = f.read()
    server_soc = socket.socket()
    server_soc.bind(('localhost', 1234))
    server_soc.listen()
    client_soc, _ = server_soc.accept()
    client_soc.send(str(len(data)).rjust(16, '0').encode())
    client_soc.sendall(data)


# client (receiver)
import socket

if __name__ == '__main__':
    soc = socket.socket()
    soc.connect(('6.tcp.eu.ngrok.io', 19717))
    data_len = int(soc.recv(16).decode())
    with open('new.mp4', 'wb') as f:
        read = 0
        while read < data_len:
            f.write(soc.recv(4096))
            read += 4096

问题在于,在互联网上,接收到的文件大小超过了发送文件大小的一半。

python sockets video-streaming
1个回答
0
投票
    while read < data_len:
        f.write(soc.recv(4096))
        read += 4096

您盲目地假设

recv
将返回 4096 字节。但是,给定的数字只是
recv
要求返回的最大字节数,它可能会返回更少。所以你需要实际检查一下你得到了什么,即类似这样的东西

    while read < data_len:
         data = soc.recv(4096)
         if not data:
              break # peer has closed
         read += len(data)
         f.write(data)
© www.soinside.com 2019 - 2024. All rights reserved.