
#include "sockets_echo_session.h"
#include <boost/bind.hpp>
namespace sockets {
    
    echo_session::echo_session(
        boost::asio::io_service& io_service
    ) :
    socket(
        io_service
    ) {
    }
    
    boost::asio::ip::tcp::socket& echo_session::get_socket(
    ) {
        return socket;
    }
    
    void echo_session::start(
    ) {
        socket.async_read_some(
            boost::asio::buffer(
                input,
                max_input
            ),
            boost::bind(
                &echo_session::handle_read,
                this,
                boost::asio::placeholders::bytes_transferred,
                boost::asio::placeholders::error
            )
        );
    }
    
    void echo_session::handle_write(
        boost::system::error_code const& error
    ) {
        if (
            error
        ) {
            delete this;
            return;
        }
        socket.async_read_some(
            boost::asio::buffer(
                input,
                max_input
            ),
            boost::bind(
                &echo_session::handle_read,
                this,
                boost::asio::placeholders::bytes_transferred,
                boost::asio::placeholders::error
            )
        );
    }
    
    void echo_session::handle_read(
        std::size_t received,
        boost::system::error_code const& error
    ) {
        if (
            error
        ) {
            delete this;
            return;
        }
        boost::asio::async_write(
            socket,
            boost::asio::buffer(
                input,
                received
            ),
            boost::bind(
                &echo_session::handle_write,
                this,
                boost::asio::placeholders::error
            )
        );
    }
}
