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

时间:2012-10-27 04:56:26

标签: 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));
}

服务器

//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)。

3 个答案:

答案 0 :(得分:7)

在阅读

之前,您需要寻找文件的开头
fseek(picture, 0, SEEK_END);
size = ftell(picture);
fseek(picture, 0, SEEK_SET);

或使用fstat获取文件大小。

答案 1 :(得分:0)

检查freadfwrite语法:

size_t fread(void *ptr, size_t size, size_t n, FILE *fp);

size_t fwrite(const void *ptr, size_t size, size_t n, FILE *fp);

在您的情况下,正确的陈述应该是:

fread(send_buffer, sizeof(send_buffer), 1, picture);

fwrite(p_array, sizeof(p_array), 1,image);

答案 2 :(得分:0)

尽管这是一篇老文章,但我必须在原始代码中强调一些问题:

    fopen之后,
  • feof(picture)始终为false。调用feof之前,您必须始终进行阅读
  • read(new_sock,p_array,size)不保证读取size字节,它取决于size的值,网络负载,服务器负载...

正确的(至少更可靠的)版本应该是:

//Send Picture as Byte Array (without need of a buffer as large as the image file)
printf("Sending Picture as Byte Array\n");
char send_buffer[BUFSIZE]; // no link between BUFSIZE and the file size
int nb = fread(send_buffer, 1, sizeof(send_buffer), picture);
while(!feof(picture)) {
    write(sock, send_buffer, nb);
    nb = fread(send_buffer, 1, sizeof(send_buffer), picture);
    // no need to bzero
}

服务器端存在相同问题:

//Read Picture Byte Array
printf("Reading Picture Byte Array\n");
char p_array[size];
char* current = p_array;
int nb = read(new_sock, current, size);
while (nb >= 0) {
    current = current + nb;
    nb = read(new_sock, current, size);
}

在服务器端,您可以避免创建与图像文件一样大的缓冲区(这可能与大图像有关):

//Read Picture Byte Array and Copy in file
printf("Reading Picture Byte Array\n");
char p_array[BUFSIZE];
FILE *image = fopen("c1.png", "w");
int nb = read(new_sock, p_array, BUFSIZE);
while (nb >= 0) {
    fwrite(p_array, 1, nb, image);
    nb = read(new_sock, p_array, BUFSIZE);
}
fclose(image);