以下是一个最近练手的简单的C++ Web服务器示例代码,献丑了:
#include <iostream>
#include <string>
#include <asio.hpp>
using asio::ip::tcp;
std::string make_http_response(const std::string& request) {
std::string response = "HTTP/1.1 200 OK\r\n";
response += "Content-Type: text/html\r\n";
response += "Content-Length: ";
response += std::to_string(22); // 示例内容长度
response += "\r\n\r\n";
response += "<html><body><h1>Hello from C++ Web Server!</h1></body></html>";
return response;
}
void handle_connection(tcp::socket socket) {
try {
std::array<char, 1024> buf;
size_t len = socket.read_some(asio::buffer(buf));
std::string request(buf.data(), len);
std::string response = make_http_response(request);
asio::write(socket, asio::buffer(response));
} catch (std::exception& e) {
std::cerr << "Exception in handle_connection: " << e.what() << std::endl;
}
}
int main(int argc, char* argv[]) {
try {
if (argc != 2) {
std::cerr << "Usage: server <port>\n";
return 1;
}
int port = std::stoi(argv[1]);
asio::io_context io_context;
tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), port));
for (;;) {
tcp::socket socket(io_context);
acceptor.accept(socket);
std::thread(handle_connection, std::move(socket)).detach();
}
io_context.run();
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}
- 这个示例仅处理HTTP GET请求,并且响应是硬编码的HTML字符串。在真实的应用程序中,您可能需要解析HTTP请求,并根据请求的内容动态生成响应。
- 该服务器为每个连接创建一个新的线程。在生产环境中,您可能需要使用线程池或异步I/O来提高性能。
- 错误处理在这个示例中非常简单。在真实的应用程序中,您可能需要更详细地处理各种可能的错误情况。
- 编译此代码时,请确保链接到Asio库。例如,使用g++编译器时,可能需要添加
-lasio
选项。