Отправка файла .mp4 через сокеты в python3 - PullRequest
0 голосов
/ 27 января 2019

Я пытаюсь сделать две маленькие программы;один из них - сервер, который будет получать файлы mp4 от клиента.Клиент - это просто небольшая программа, которая отправляет файл .mp4, расположенный в его папке.

Я могу полностью отправить файл mp4, и файл такого же размера создан, но по какой-то причине mp4 получаетповрежден или что-то еще идет не так, и я не могу воспроизвести файл mp4 в проигрывателе QuickTime или VLC.

Я не понимаю этого, так как копирую все байты и отправляю все затем небольшими пакетами.Буду очень признателен за помощь или советы.

Код сервера:

#!/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()

1 Ответ

0 голосов
/ 27 января 2019

Исправьте ошибки в коде вашего сервера:

#!/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) 
...