C++语言最小化http服务器代码
时间: 2023-09-24 16:05:59 浏览: 40
以下是使用C++编写的最小化HTTP服务器代码示例:
```
#include <iostream>
#include <string>
#include <sstream>
#include <boost/asio.hpp>
using namespace std;
using boost::asio::ip::tcp;
string build_response(const string& message) {
stringstream response;
response << "HTTP/1.1 200 OK\r\n";
response << "Content-Type: text/plain\r\n";
response << "Content-Length: " << message.length() << "\r\n";
response << "Connection: close\r\n\r\n";
response << message;
return response.str();
}
int main() {
try {
boost::asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 80));
while (true) {
tcp::socket socket(io_service);
acceptor.accept(socket);
stringstream message;
boost::asio::streambuf buffer;
boost::asio::read_until(socket, buffer, "\r\n\r\n");
message << &buffer;
string response = build_response("Hello, World!");
boost::asio::write(socket, boost::asio::buffer(response));
socket.shutdown(tcp::socket::shutdown_both);
socket.close();
}
} catch (exception& e) {
cerr << "Exception: " << e.what() << endl;
}
return 0;
}
```
该代码使用了 Boost.Asio 库来实现一个最小化的 HTTP 服务器。它监听本地 80 端口,接收客户端连接,读取客户端发送的数据,然后发送一个简单的 "Hello, World!" 响应。