
#include "sockets_echo_server.h"
#include <boost/bind.hpp>
namespace sockets {
    
    echo_server::echo_server(
        boost::asio::io_service& io_service
    ) :
    acceptor(
        io_service
    ) {
        acceptor.async_connect(
            boost::asio::ip::tcp::endpoint(
                boost::asio::ip::address::from_string(
                    "127.0.0.1"
                ),
                7654
            ),
            boost::bind(
                &echo_server::handle_connect,
                this,
                boost::asio::placeholders::error
            )
        );
    }
    
    void echo_server::handle_connect(
        boost::system::error_code const& error
    ) {
        if (
            error
        ) {
            return;
        }
        echo_session* connecting = new echo_session(
            acceptor.get_io_service(
            )
        );
        acceptor.async_accept(
            connecting->get_socket(
            ),
            boost::bind(
                &echo_server::handle_accept,
                this,
                connecting,
                boost::asio::placeholders::error
            )
        );
    }
    
    void echo_server::handle_accept(
        echo_session* connected,
        boost::system::error_code const& error
    ) {
        if (
            error
        ) {
            delete connected;
            return;
        }
        connected->start(
        );
        echo_session* connecting = new echo_session(
            acceptor.get_io_service(
            )
        );
        acceptor.async_accept(
            connecting->get_socket(
            ),
            boost::bind(
                &echo_server::handle_accept,
                this,
                connecting,
                boost::asio::placeholders::error
            )
        );
    }
}
