5 // Copyright (c) 2003-2012 Christopher M. Kohlhoff (chris at kohlhoff dot com)
7 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
14 #include <boost/bind.hpp>
15 #include <boost/shared_ptr.hpp>
16 #include <boost/enable_shared_from_this.hpp>
17 #include <boost/asio.hpp>
19 using boost::asio::ip::tcp;
21 std::string make_daytime_string()
23 using namespace std; // For time_t, time and ctime;
29 : public boost::enable_shared_from_this<tcp_connection>
32 typedef boost::shared_ptr<tcp_connection> pointer;
34 static pointer create(boost::asio::io_service& io_service)
36 return pointer(new tcp_connection(io_service));
46 message_ = make_daytime_string();
48 boost::asio::async_write(socket_, boost::asio::buffer(message_),
49 boost::bind(&tcp_connection::handle_write, shared_from_this(),
50 boost::asio::placeholders::error,
51 boost::asio::placeholders::bytes_transferred));
55 tcp_connection(boost::asio::io_service& io_service)
60 void handle_write(const boost::system::error_code& /*error*/,
61 size_t /*bytes_transferred*/)
72 tcp_server(boost::asio::io_service& io_service)
73 : acceptor_(io_service, tcp::endpoint(tcp::v4(), 13))
81 tcp_connection::pointer new_connection =
82 tcp_connection::create(acceptor_.get_io_service());
84 acceptor_.async_accept(new_connection->socket(),
85 boost::bind(&tcp_server::handle_accept, this, new_connection,
86 boost::asio::placeholders::error));
89 void handle_accept(tcp_connection::pointer new_connection,
90 const boost::system::error_code& error)
94 new_connection->start();
100 tcp::acceptor acceptor_;
107 boost::asio::io_service io_service;
108 tcp_server server(io_service);
111 catch (std::exception& e)
113 std::cerr << e.what() << std::endl;