使用基本的Linux系统调用来创建一个TCP socket,监听端口8080,并在接受到客户端连接时创建一个新的线程来处理连接。每个连接处理函数都是一个独立的线程,读取客户端请求并发送固定的HTTP响应。
代码:
#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
const int BUFFER_SIZE = 1024;
void *connection_handler(void *socket_desc) {
int sock = *(int *)socket_desc;
char buffer[BUFFER_SIZE];
std::string response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\nHello, World!";
// 读取客户端请求
ssize_t read_size = read(sock, buffer, BUFFER_SIZE - 1);
if (read_size > 0) {
buffer[read_size] = '\0';
std::cout << "Received request:\n" << buffer << std::endl;
// 发送响应
write(sock, response.c_str(), response.length());
}
// 关闭连接
close(s