#include#include using boost::asio::ip::tcp; void handle_client(tcp::socket socket) { boost::asio::streambuf buffer; boost::asio::read_until(socket, buffer, std::string("\n")); std::istream is(&buffer); std::string msg; std::getline(is, msg); std::cout << "Received from client: " << msg << std::endl; } int main() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 12345)); while (true) { tcp::socket socket(io_context); acceptor.accept(socket); handle_client(std::move(socket)); } return 0; }
#includeBoth of these examples use the Boost C++ library's asio package, which provides an asynchronous I/O service that can be used for creating network applications.#include #include using boost::asio::ip::tcp; std::string get_response(std::string request) { std::stringstream ss; ss << "HTTP/1.1 200 OK\r\n"; ss << "Content-Type: text/plain\r\n"; ss << "Content-Length: " << 13 << "\r\n"; ss << "\r\n"; ss << "Hello, World!"; return ss.str(); } void handle_client(tcp::socket socket) { boost::asio::streambuf buffer; boost::asio::read_until(socket, buffer, "\r\n\r\n"); std::istream is(&buffer); std::string request; std::getline(is, request); std::string response = get_response(request); boost::asio::write(socket, boost::asio::buffer(response)); } int main() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 80)); while (true) { tcp::socket socket(io_context); acceptor.accept(socket); handle_client(std::move(socket)); } return 0; }