#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <dirent.h>
#include <signal.h>
#define PORT 8888
#define WEB_ROOT “./web”
#define MAX_THREADS 100
void log_request(const char *method, const char *path, int status)
{
printf(“[%s] %s -> %d\n”, method, path, status);
}
void send_response(int sock, int status, const char *content_type, const char *body, int body_len)
{
char header[512];
sprintf(header, “HTTP/1.1 %d OK\r\nContent-Type: %s\r\nContent-Length: %d\r\n\r\n”,
status, content_type, body_len);
size_t result = 0; result = send(sock, header, strlen(header), 0); if (result == -1) { close(sock); } result = send(sock, body, body_len, 0); if (result == -1) { close(sock); }
}
void *handle_request(void *arg)
{
int sock = *(int *)arg;
char buffer[4096];
recv(sock, buffer, sizeof(buffer), 0);
char method[16], path[256]; sscanf(buffer, "%s %s", method, path); if (strcmp(method, "GET") == 0) { char filepath[512]; if (strcmp(path, "/") == 0) { strcpy(path, "/Index.html"); } sprintf(filepath, "%s%s", WEB_ROOT, path); FILE *file = fopen(filepath, "rb"); if (file) { fseek(file, 0, SEEK_END); long len = ftell(file); fseek(file, 0, SEEK_SET); char *content = malloc(len); fread(content, 1, len, file); fclose(file); const char *content_type = "text/html"; if (strstr(path, ".css")) { content_type = "text/css"; } else if (strstr(path, ".js")) { content_type = "application/json"; } else if (strstr(path, ".png")) { content_type = "image/png"; } else if (strstr(path, ".jpg")) { content_type = "image/jpeg"; } send_response(sock, 200, content_type, content, len); free(content); log_request(method, path, 200); } else { const char *not_found = "<h1>404 Not Found</h1>"; send_response(sock, 404, "text/html", not_found, strlen(not_found)); log_request(method, path, 404); } } close(sock); return NULL;
}
int main()
{
signal(SIGPIPE, SIG_IGN);
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_port = htons(PORT),
.sin_addr.s_addr = htonl(INADDR_ANY)};
bind(server_fd, (struct sockaddr *)&addr, sizeof(addr)); listen(server_fd, 10); printf("Threaded server running on port %d\n", PORT); while (1) { int client_fd = accept(server_fd, NULL, NULL); pthread_t tid; int *sock_ptr = malloc(sizeof(int)); *sock_ptr = client_fd; pthread_create(&tid, NULL, handle_request, sock_ptr); pthread_detach(tid); } return 0;
}
在此基础上拓展post功能
最新发布