#include #include #include "connection.h" connection::connection(boost::asio::io_service& ioService, const context& context) : m_ioService(ioService), m_socket(ioService), m_protocol(context) { } boost::asio::ip::tcp::socket& connection::socket() { return m_socket; } void connection::start() { start_write(m_protocol.openConnection(m_socket.remote_endpoint().address().to_string()).second); } void connection::start_read() { m_socket.async_read_some(boost::asio::buffer(m_data), boost::bind(&connection::handle_read, this, _1, _2)); } void connection::handle_read(const boost::system::error_code& ec, std::size_t length) { if (!ec) { protocol::result result = m_protocol.processMessage(std::string(m_data.begin(), m_data.begin() + length)); if (result.second.size() > 0) start_write(result.second); else start_read(); if (result.first == protocol::state::disconnected) m_socket.close(); } } void connection::start_write(const std::string& message) { std::copy(message.begin(), message.end(), m_data.data()); size_t length = message.size() + 1; m_data[message.size()] = '\n'; boost::asio::async_write(m_socket, boost::asio::buffer(m_data, length), boost::bind(&connection::handle_write, this, _1)); } void connection::handle_write(const boost::system::error_code& ec) { if (!ec) start_read(); }