Mercurial
diff seobeo/main.c @ 4:0b3b4f5887bb
[Seobeo] Updated so that it create socket for both server and clients.
| author | June Park <parkjune1995@gmail.com> |
|---|---|
| date | Fri, 26 Sep 2025 15:14:46 -0700 |
| parents | 2758f5527d2b |
| children | 3e12bf044589 |
line wrap: on
line diff
--- a/seobeo/main.c Wed Sep 24 18:49:09 2025 -0700 +++ b/seobeo/main.c Fri Sep 26 15:14:46 2025 -0700 @@ -18,10 +18,11 @@ errno = saved_errno; } -void HandleClientRequest(int client_fd) +void HandleClientRequest(Seobeo_PHandle cli) { size_t idx = Dowa_HashMap_GetPosition(cache, "index.html"); - Dowa_PHashEntry entry = cache->entries[idx]; + Dowa_PHashEntry entry = cache->entries[idx]; + if (!entry) { // 404 response if missing const char *not_found = @@ -29,8 +30,8 @@ "Content-Length: 0\r\n" "Connection: close\r\n" "\r\n"; - send(client_fd, not_found, strlen(not_found), 0); - close(client_fd); + send(cli->socket, not_found, strlen(not_found), 0); + Seobeo_Handle_Destroy(cli); return; } @@ -48,40 +49,29 @@ char *header = malloc(header_len + 1); if (!header) { perror("malloc"); - close(client_fd); return; } snprintf(header, header_len + 1, template, body_size); - // 4) Send header - send(client_fd, header, header_len, 0); + Seobeo_Handle_QueueData(cli, + (const uint8*)header, + (uint32)(header_len + 1)); free(header); - // 5) Stream the body in a loop until everything is sent - ssize_t total_sent = 0; - const char *body = entry->buffer; - while ((size_t)total_sent < body_size) - { - ssize_t sent = send( - client_fd, - body + total_sent, - body_size - total_sent, - 0 - ); - if (sent <= 0) - { - // error or connection closed by client - break; - } - total_sent += sent; - } + Seobeo_Handle_QueueData(cli, + (const uint8*)entry->buffer, + (uint32)body_size); - // 6) Tear down - close(client_fd); + + Seobeo_Handle_Flush(cli); + + Seobeo_Handle_Destroy(cli); } int main(void) { + struct sigaction sa; + cache = Dowa_HashMap_Create(1024); if (Dowa_Cache_Folder(cache, "seobeo/pages") != 0) { @@ -89,7 +79,10 @@ return -1; } - struct sigaction sa; + Seobeo_PHandle srv = Seobeo_Stream_Handle_Create(NULL, "8080"); + + if (srv->socket < 0) return 1; + printf("Listening on port 8080\n"); sa.sa_handler = SigchildHandler; // reap all dead processes sigemptyset(&sa.sa_mask); @@ -98,10 +91,23 @@ perror("sigaction"); exit(1); } - - int sock_fd = Seobeo_CreateSocket(1, "6969", 10); - Seobeo_ListenClient(sock_fd, &HandleClientRequest); + + while (1) { + Seobeo_PHandle cli = Seobeo_Stream_Handle_Accept(srv); + if (cli == NULL) + { + continue; + } + printf("connected to %s\n", cli->host); + if (!fork()) + { + HandleClientRequest(cli); + exit(0); + } + Seobeo_Handle_Destroy(cli); + } + + Seobeo_Handle_Destroy(srv); return 0; } -