Hello,
I'm trying to send some binary data, such as an animated gif, via an HTTP response for a simple web server.
I am having issues having the browser close the connection after receipt of the data.
I create the header such as:
"HTTP/1.1 200 OK
Content-Length: <file size>
Content-Type: <file type>
<binary data>"
This is stored in a malloc'ed char *.
To add the binary data I'm using fread:
fread(request + strlen(request), 1, size, fp)
I then write 'total' bits via connfd:
write(connfd, request, total)
where total = strlen(headerRequest) + size + 3 (for ending \r\n\0).
The writing seems to be okay however the image doesn't load and the browser still seems to be waiting for data. I was wondering if you could assist.
If I added "Connection: close" to the header and closed connfd myself the page loads fine. Obviously, for efficiency purposes, I'd rather only close connfd once read() returns 0.
If anyone could be of assistance that would be great.
Further information available on request.
Thank you for your time.
The header creation code is below:
=======
Code:
/* Try to get file */
strcat(cwd, file);
if(endsWith (cwd, ".html") || endsWith(cwd, ".htm")) {
strcpy(fileType, "text/html");
binary = 0;
} else if (endsWith(cwd, ".txt")) {
strcpy(fileType, "text/plain");
binary = 0;
} else if (endsWith(cwd, ".jpg") || endsWith(cwd, ".jpeg")) {
strcpy(fileType, "image/jpeg");
binary = 1;
} else if (endsWith(cwd, ".gif")) {
strcpy(fileType, "image/gif");
binary = 1;
} else {
strcpy(fileType, "application/octet-stream");
binary = 1;
}
if (!binary) {
if ((fp = fopen(cwd, "r")) == NULL) {
return errorFileNotFound(connfd);
}
} else {
if ((fp = fopen(cwd, "rb")) == NULL) {
return errorFileNotFound(connfd);
}
}
size = getFileSize(fp);
/* Total malloc is header length + size + 3 (3 for terminating \r\n\0) */
printf("%s has size %ld bytes.\n", cwd, size);
headerRequest = getHeader(fileType, size);
total = strlen(headerRequest) + size + 3;
request = malloc(total);
if (request == NULL) {
return internalError(connfd);
}
request[0] = '\0';
strcat(request, headerRequest);
free(headerRequest);
char filepart[MAXLINE];
filepart[0] = '\0';
if (!binary) {
while (fgets(filepart, MAXLINE, fp) != NULL) {
strcat(request, filepart);
}
strcat(request, "\r\n");
} else {
read = fread(request+strlen(request), 1, size, fp);
request[total - 3] = '\r';
request[total - 2] = '\n';
request[total - 1] = '\0';
}
printf("%lu bytes read\n", read);
fclose(fp);
printf("\nResponse\n----\n%s\n---\n", request);
if ((written = write(connfd, request, total)) == -1) {
printError("Error writing to client.");
free(request);
return internalError(connfd);
}
printf("%lu written, told server I'd send %lu\n", written, total);
free(request);
return 0;