我正在尝试通过 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));
}
服务器
//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);
编辑:修复了服务器代码中的 sizeof(int)。