From 7901ad145df42c510ffdccf705f26511a6f7ba4d Mon Sep 17 00:00:00 2001 From: dan Date: Tue, 14 Jan 2025 11:13:17 -0500 Subject: [PATCH] Added delay to ensure all data gets sent before shutdown --- src/server.c | 34 ++++++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/src/server.c b/src/server.c index b7458aa..e288247 100644 --- a/src/server.c +++ b/src/server.c @@ -261,23 +261,41 @@ void handle_client(int client_socket) { printf("Got data of length: %d\n", length); // HTTP response - const char *http_response_fmt = + const char *http_headers_fmt = "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" - "Content-Length: %d\r\n" + "Content-Length: %u\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(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 + shutdown(client_socket, SHUT_WR); + sleep(1); close(client_socket); - free(http_response); free(data); }