user1350184
user1350184

Reputation:

Sending large files (images) over internet using a C server

I am creating a simple webserver in C using sockets, it listens on port 10001; so far it works and I can load all images fine in my browser when I use http://127.0.0.1:10001/. But when I try to access it on the website all the images larger than 4kb don't get displayed, and when I open them individually it only shows about 1/3th of the image.

I have a nameserver redirect traffic to my router at port 80, which then in turn forwards it to port 10001 on my local machine.

The files get send like this (in this case a jpeg image):

FILE *fp;
char *buf, header[1024];
int fsize, hsize, nbytes;
struct tm *itime;
time_t rawtime;

fp = fopen(file, "r");

fseek(fp, 0, SEEK_END);
fsize = ftell(fp);
rewind(fp);

time(&rawtime);
itime = localtime(&rawtime);

hsize = sprintf(header, "HTTP/1.1 200 OK\r\n"
                        "Server: iserv\r\n"
                        "Date: %s"
                        "Content-Length: %d\r\n"
                        "Content-Type: image/jpeg\r\n"
                        "Accept-Ranges: bytes\r\n"
                        "Connection: keep-alive\r\n\r\n", asctime(itime), fsize);

write(fd, header, hsize);

buf = (char*)malloc(CHUNK_SIZE);
while((nbytes = fread(buf, sizeof(char), CHUNK_SIZE, fp)) > 0)
    write(fd, buf, nbytes);

free(buf);

Why does this problem occur, and how can I solve it?

Upvotes: 0

Views: 623

Answers (1)

abligh
abligh

Reputation: 25129

Your write() is not writing the whole data out because your socket is set to non-blocking and you are not checking the amount written. The simplest fix is to clear O_NONBLOCK with fcntl(fd, FSET_FL ...).

Upvotes: 0

Related Questions