#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>
#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);
}
// 发送HTTP响应
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);
send(sock, header, strlen(header), 0);
send(sock, body, body_len, 0);
}
// 处理HTTP请求
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);
// 根据扩展名设置Content-Type
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()
{
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;
}
运行一段时间后程序会自动退出,怎么分析原因
最新发布