在C中通过套接字发送图像

Tak*_*kun 3 c sockets

我正在尝试通过C中的TCP套接字发送图像文件,但图像未在服务器端正确重新组装.我想知道是否有人可以指出错误?

我知道服务器正在接收正确的文件大小,它构造了一个大小的文件,但它不是一个图像文件.

客户

//Get Picture Size
printf("Getting Picture Size\n");
FILE *picture;
picture = fopen(argv[1], "r");
int size;
fseek(picture, 0, SEEK_END);
size = ftell(picture);

//Send Picture Size
printf("Sending Picture Size\n");
write(sock, &size, sizeof(size));

//Send Picture as Byte Array
printf("Sending Picture as Byte Array\n");
char send_buffer[size];
while(!feof(picture)) {
    fread(send_buffer, 1, sizeof(send_buffer), picture);
    write(sock, send_buffer, sizeof(send_buffer));
    bzero(send_buffer, sizeof(send_buffer));
}
Run Code Online (Sandbox Code Playgroud)

服务器

//Read Picture Size
printf("Reading Picture Size\n");
int size;
read(new_sock, &size, sizeof(int));

//Read Picture Byte Array
printf("Reading Picture Byte Array\n");
char p_array[size];
read(new_sock, p_array, size);

//Convert it Back into Picture
printf("Converting Byte Array to Picture\n");
FILE *image;
image = fopen("c1.png", "w");
fwrite(p_array, 1, sizeof(p_array), image);
fclose(image);
Run Code Online (Sandbox Code Playgroud)

编辑:修复服务器代码中的sizeof(int).

iab*_*der 7

你需要在阅读之前寻找文件的开头

fseek(picture, 0, SEEK_END);
size = ftell(picture);
fseek(picture, 0, SEEK_SET);
Run Code Online (Sandbox Code Playgroud)

或用于fstat获取文件大小.