利用Socket或TcpClient/TcpListener,编写一个HTTP服务器c++
时间: 2024-02-19 14:02:47 浏览: 144
编写一个 HTTP 服务器涉及到很多复杂的工作,需要深入了解 HTTP 协议和网络编程。以下是一个基本的 C++ HTTP 服务器的示例代码,基于 Socket:
```c++
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
int server_fd, client_fd;
struct sockaddr_in server_addr, client_addr;
char buffer[BUFFER_SIZE] = {0};
int addrlen = sizeof(server_addr);
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
if (bind(server_fd, (struct sockaddr*)&server_addr, addrlen) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
printf("HTTP Server listening on port %d...\n", PORT);
while (true) {
if ((client_fd = accept(server_fd, (struct sockaddr*)&client_addr, (socklen_t*)&addrlen)) < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
// Read the incoming request
memset(buffer, 0, BUFFER_SIZE);
read(client_fd, buffer, BUFFER_SIZE - 1);
// Print the incoming request
printf("%s\n", buffer);
// Send a response
const char* response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<html><body><h1>Hello, World!</h1></body></html>";
write(client_fd, response, strlen(response));
// Close the client socket
close(client_fd);
}
return 0;
}
```
这个示例代码使用了 Socket 编程接口,并且监听了本地的 8080 端口。当有客户端连接进来后,服务器会读取客户端发送的请求,并且发送一个简单的 HTML 响应。这个示例代码只是一个基本的演示,实际的 HTTP 服务器需要处理更多的细节和错误情况。
阅读全文