I'm working on writing a simple web server in C,and I want to send a image~17KB to the browser. I'm trying to do it with send() function,but the buffer I defined is only 4096 and I don't want to change it.So I want to divide the image into byte chunks to send,but the browser just seem to receive the response header and the image can't load.And if I change the BUF_SIZE to 1024*32 and send the all the image,it will work.
What should I do to send the image?I would appreciate it if you could give me a suggestion. My code as follow:
#define BUF_SIZE 4096
char buf[BUF_SIZE];
readret=sprintf(buf,"HTTP/1.1 200 OK\r\n"
"Content-Length: %ld\r\n"
"Content-type: image/png"
"Accept-Ranges: bytes\r\n\r\n");
FILE *fp=fopen(file,"rb");
if (send(client_sock, buf, readret, 0) != readret){
close_socket(client_sock);
close_socket(sock);
fprintf(stderr, "Error sending to client.\n");
return EXIT_FAILURE;
}
if(fp){
while((readret=fread(buf,sizeof(unsigned char),BUF_SIZE,fp))>0){
if (send(client_sock, buf, readret, 0) != readret){
close_socket(client_sock);
close_socket(sock);
fprintf(stderr, "Error sending to client.\n");
return EXIT_FAILURE;
}
}
fclose(fp);
}
The browser as follow:
The response header of the image
Edit 2022/3/25
I delete parameter to the %ld by mistake,sorry
CodePudding user response:
I got the reason:I add a blank to the end of ervery chunk carelessly.In other words, the image'data is error.Thank every one of you!