Skip to content

Instantly share code, notes, and snippets.

@edouarda
Last active February 13, 2018 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edouarda/3a0cacdaacf5400e56ede0d078e862b0 to your computer and use it in GitHub Desktop.
Save edouarda/3a0cacdaacf5400e56ede0d078e862b0 to your computer and use it in GitHub Desktop.
#include <boost/asio.hpp>
#include <iostream>
class session : public std::enable_shared_from_this<session>
{
public:
explicit session(boost::asio::ip::tcp::socket && s)
: _socket{std::move(s)}
{}
private:
void update_time()
{
auto t = std::chrono::system_clock::to_time_t(
std::chrono::system_clock::now());
_len = !::ctime_s(_buffer.data(), _buffer.size(), &t)
? ::strnlen_s(_buffer.data(), _buffer.size())
: 0u;
}
private:
void write_time()
{
auto ref = shared_from_this();
boost::asio::async_write(_socket,
boost::asio::const_buffer{_buffer.data(), _len},
[ref](boost::system::error_code ec, size_t) {
ref->_socket.shutdown(
boost::asio::socket_base::shutdown_both, ec);
ref->_socket.close(ec);
});
}
public:
void response()
{
update_time();
write_time();
}
private:
boost::asio::ip::tcp::socket _socket;
std::array<char, 128> _buffer;
size_t _len{0};
};
using session_ptr = std::shared_ptr<session>;
static void write_time(session_ptr s)
{
s->response();
}
static void do_accept(boost::asio::ip::tcp::acceptor & acc)
{
acc.async_accept(
[&acc](boost::system::error_code ec, boost::asio::ip::tcp::socket s) {
if (ec) return;
write_time(std::make_shared<session>(std::move(s)));
do_accept(acc);
});
}
int main(int, char **)
{
boost::asio::io_context context{1};
auto ip = boost::asio::ip::address::from_string("127.0.0.1");
auto ep = boost::asio::ip::tcp::endpoint{ip, 8080};
boost::asio::ip::tcp::acceptor acc{context, ep};
do_accept(acc);
boost::asio::io_context::work w{context};
boost::system::error_code ec;
while (!ec)
{
context.run(ec);
}
acc.close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment