Last active
September 23, 2015 00:33
-
-
Save Tosainu/ac7392b38f0981ac6177 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <boost/asio.hpp> | |
auto main(int argc, char** argv) -> int { | |
if (argc != 3) { | |
std::cerr << "Usage: " << argv[0] << " <ip> <port>" << std::endl; | |
return 1; | |
} | |
boost::asio::io_service io; | |
try { | |
const auto ip = boost::asio::ip::address::from_string(argv[1]); | |
const auto port = std::atoi(argv[2]); | |
boost::asio::ip::tcp::endpoint endpoint(ip, port); | |
boost::asio::ip::tcp::acceptor acceptor(io, endpoint); | |
boost::asio::ip::tcp::socket socket(io); | |
{ | |
std::cout << "Server running at http://" << ip.to_string() << ":" << port << "/\n\n"; | |
acceptor.accept(socket); | |
{ | |
// Read request | |
// -------------------------------- | |
boost::asio::streambuf buf; | |
std::istream buf_stream(&buf); | |
// request line | |
std::string method; | |
std::string request_uri; | |
std::string http_version; | |
boost::asio::read_until(socket, buf, "\r\n"); | |
buf_stream >> method >> request_uri >> http_version; | |
std::cout << "- Request-Line ----------------------\n" | |
<< "Method: " << method << "\n" | |
<< "Request-URI: " << request_uri << "\n" | |
<< "HTTP-Version: " << http_version << "\n\n"; | |
// remove \r\n | |
buf.consume(2); | |
// headers | |
boost::asio::read_until(socket, buf, "\r\n\r\n"); | |
std::cout << "- Request-Header --------------------\n" | |
<< &buf; | |
} | |
{ | |
// Write response | |
// -------------------------------- | |
const std::string message_body("Hello World!!"); | |
// status line | |
boost::asio::write(socket, boost::asio::buffer("HTTP/1.1 200 Ok\r\n")); | |
// headers | |
boost::asio::streambuf buf; | |
std::ostream buf_stream(&buf); | |
buf_stream << "Content-Length: " << message_body.length() << "\r\n" | |
<< "Content-Type: text/plain\r\n" | |
<< "Connection: close\r\n\r\n"; | |
boost::asio::write(socket, buf); | |
// message body | |
boost::asio::write(socket, boost::asio::buffer(message_body)); | |
} | |
socket.close(); | |
} | |
std::cout << std::flush; | |
} catch (std::exception& e) { | |
std::cerr << "Exception: " << e.what() << std::endl; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment