Added delay to ensure all data gets sent before shutdown
This commit is contained in:
parent
471bdb71f3
commit
7901ad145d
34
src/server.c
34
src/server.c
@ -261,23 +261,41 @@ void handle_client(int client_socket) {
|
|||||||
printf("Got data of length: %d\n", length);
|
printf("Got data of length: %d\n", length);
|
||||||
|
|
||||||
// HTTP response
|
// HTTP response
|
||||||
const char *http_response_fmt =
|
const char *http_headers_fmt =
|
||||||
"HTTP/1.1 200 OK\r\n"
|
"HTTP/1.1 200 OK\r\n"
|
||||||
"Content-Type: text/plain\r\n"
|
"Content-Type: text/plain\r\n"
|
||||||
"Content-Length: %d\r\n"
|
"Content-Length: %u\r\n"
|
||||||
"Connection: close\r\n"
|
"Connection: close\r\n"
|
||||||
"\r\n%s";
|
"\r\n";
|
||||||
|
|
||||||
|
char headers[BUFFER_SIZE];
|
||||||
|
sprintf(headers, http_headers_fmt, length);
|
||||||
|
|
||||||
|
printf("Sending headers\n");
|
||||||
|
if (send(client_socket, headers, strlen(headers), 0) == -1) {
|
||||||
|
printf("Failed to send headers\n");
|
||||||
|
free(data);
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
printf("Sent headers\n");
|
||||||
|
}
|
||||||
|
|
||||||
char *http_response = malloc(length + strlen(http_response_fmt) + 20);
|
|
||||||
if (http_response == NULL) perror("Failed to allocate HTTP response\n");
|
|
||||||
sprintf(http_response, http_response_fmt, length, data);
|
|
||||||
// Send the response to the client
|
// Send the response to the client
|
||||||
send(client_socket, http_response, strlen(http_response), 0);
|
int total_sent = 0;
|
||||||
|
|
||||||
|
while (total_sent < length) {
|
||||||
|
int amt = length - total_sent;
|
||||||
|
int sent = send(client_socket, data+total_sent, amt, 0);
|
||||||
|
printf("Tried sending %d actually sent %d\n", amt, sent);
|
||||||
|
total_sent += sent;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Closing connection\n");
|
||||||
// Close the client socket
|
// Close the client socket
|
||||||
|
shutdown(client_socket, SHUT_WR);
|
||||||
|
sleep(1);
|
||||||
close(client_socket);
|
close(client_socket);
|
||||||
|
|
||||||
free(http_response);
|
|
||||||
free(data);
|
free(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user