【问题标题】:Sending a .mp4 file over sockets in python3在 python3 中通过套接字发送 .mp4 文件
【发布时间】:2019-01-27 13:49:09
【问题描述】:

我正在尝试制作两个小程序;一个是从客户端接收 mp4 文件的服务器。客户端只是一个小程序,它发送位于其文件夹中的 .mp4 文件。

我能够完全发送 mp4 文件并创建相同大小的文件,但由于某种原因 mp4 损坏或出现其他问题,我无法在 QuickTime 播放器或 VLC 中播放 mp4 文件。

我不明白这一点,因为我正在复制所有字节,然后全部以小数据包的形式发送。非常感谢一些帮助或提示。

服务器代码:

#!/usr/bin/python3

from socket import socket, gethostname

s = socket()
host = gethostname()
port = 3399
s.bind((host, port))
s.listen(5)
n = 0

while True:
    print("Listening for connections...")
    connection, addr = s.accept()

    try:
        print("Starting to read bytes..")
        buffer = connection.recv(1024)

        with open('video_'+str(n), "wb") as video:
            n += 1
            i = 0
            while buffer:
                buffer = connection.recv(1024)
                video.write(buffer)
                print("buffer {0}".format(i))
                i += 1

        print("Done reading bytes..")
        connection.close()

    except KeyboardInterrupt:
        if connection:
            connection.close()
        break

s.close()

客户端代码:

#!/usr/bin/python3

from socket import socket, gethostname, SHUT_WR

s = socket()
host = gethostname()
port = 3399

s.connect((host, port))

print("Sending video..")

with open("test.mp4", "rb") as video:
    buffer = video.read()
    print(buffer)
    s.sendall(buffer)

print("Done sending..")
s.close()

【问题讨论】:

    标签: python-3.x file sockets video mp4


    【解决方案1】:

    修复服务器代码中的错误:

    #!/usr/bin/python3
    
    from socket import socket, gethostname
    
    s = socket()
    host = gethostname()
    port = 3399
    s.bind((host, port))
    s.listen(5)
    n = 0
    
    while True:
        print("Listening for connections...")
        connection, addr = s.accept()
    
        try:
            print("Starting to read bytes..")
            buffer = connection.recv(1024)
    
            with open('video_'+str(n)+'.mp4', "wb") as video:
                n += 1
                i = 0
                while buffer:                
                    video.write(buffer)
                    print("buffer {0}".format(i))
                    i += 1
                    buffer = connection.recv(1024)
    
            print("Done reading bytes..")
            connection.close()
    
        except KeyboardInterrupt:
            if connection:
                connection.close()
            break
    
    s.close()
    

    在这里修复:

    with open('video_'+str(n)+'.mp4', "wb") as video:
    

    这里:

    while buffer:                
        video.write(buffer)
        print("buffer {0}".format(i))
        i += 1
        buffer = connection.recv(1024) 
    

    【讨论】:

    • 啊,是的,解决了!不敢相信这是这么简单的事情,谢谢。一旦你在代码上花费了大量时间,你就会开始阅读这些东西。
    猜你喜欢
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 2012-03-12
    • 2012-07-12
    • 2015-08-28
    • 2021-07-06
    相关资源
    最近更新 更多