c++实现http服务端
时间: 2023-07-29 07:07:33 浏览: 128
c++ 实现了 http服务
要实现一个基本的HTTP服务器,你需要完成以下步骤:
1. 创建一个TCP套接字并绑定到一个端口
2. 监听传入的连接请求
3. 接受连接请求并处理客户端请求
4. 解析HTTP请求
5. 处理HTTP请求并生成HTTP响应
6. 发送HTTP响应到客户端并关闭连接
以下是一个简单的c++实现HTTP服务器的示例代码:
```c++
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
const int PORT = 8080;
const int MAX_CONNECTIONS = 10;
int main() {
int server_socket, client_socket;
struct sockaddr_in server_address, client_address;
char buffer[1024] = {0};
// 创建一个套接字
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
cerr << "Failed to create socket" << endl;
exit(EXIT_FAILURE);
}
// 绑定套接字到指定端口
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = htons(PORT);
if (bind(server_socket, (struct sockaddr *) &server_address, sizeof(server_address)) == -1) {
cerr << "Failed to bind socket to port " << PORT << endl;
exit(EXIT_FAILURE);
}
// 监听传入的连接请求
if (listen(server_socket, MAX_CONNECTIONS) == -1) {
cerr << "Failed to listen for connections" << endl;
exit(EXIT_FAILURE);
}
cout << "Server listening on port " << PORT << endl;
// 接受连接请求并处理客户端请求
while (true) {
socklen_t client_address_size = sizeof(client_address);
client_socket = accept(server_socket, (struct sockaddr *) &client_address, &client_address_size);
if (client_socket == -1) {
cerr << "Failed to accept connection" << endl;
continue;
}
cout << "Client connected: " << inet_ntoa(client_address.sin_addr) << endl;
// 读取客户端发送的HTTP请求
memset(buffer, 0, sizeof(buffer));
if (read(client_socket, buffer, sizeof(buffer)) == -1) {
cerr << "Failed to read HTTP request" << endl;
close(client_socket);
continue;
}
cout << "Received HTTP request:" << endl << buffer << endl;
// 处理HTTP请求并生成HTTP响应
const char *response = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\nHello World!";
int response_length = strlen(response);
// 发送HTTP响应到客户端并关闭连接
if (write(client_socket, response, response_length) == -1) {
cerr << "Failed to send HTTP response" << endl;
}
cout << "Sent HTTP response:" << endl << response << endl;
close(client_socket);
cout << "Client disconnected" << endl;
}
return 0;
}
```
这个示例代码创建了一个TCP套接字并绑定到8080端口。它监听传入的连接请求,接受连接请求并处理客户端请求。当客户端发送HTTP请求时,它读取HTTP请求并生成HTTP响应,然后将响应发送回客户端并关闭连接。
请注意,这只是一个简单的示例代码,并不具有完整的HTTP服务器功能。如果你想要实现一个完整的HTTP服务器,你需要考虑更多的因素,比如线程管理、错误处理、安全性等。
阅读全文