通过python3中的套接字发送.mp4文件

时间:2019-01-27 13:49:10

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

我正在尝试制作两个小程序;一个是服务器,它将从客户端接收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()

1 个答案:

答案 0 :(得分:0)

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

input = realloc(input, len + 1);
input[len] = ch;
len++;

在这里修复:

#include <stdio.h>
#include <stdlib.h>


int main(void)
{
    int len = 0;
    char *input = malloc(1);
    input[0] = '\0';

    int ch;
    while ((ch = getchar()) != '\n')
    {
        input = realloc(input, len + 1);
        input[len] = ch;
        len++;
    }
    input[len] = '\0';

    printf("You entered: %s\n", input);
    printf("Length of str: %d\n", len);

    free(input);
    return 0;
}

在这里:

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