#include "connection.h" #include Connection::Connection(boost::asio::io_service& io_service) : socket(io_service) { } void Connection::handle_read(uint8_t* data, std::size_t bytes, const boost::system::error_code& error_code) { if(error_code) { error("Read error."); return; } got_data(data, bytes); delete[] data; } void Connection::handle_write() { } void Connection::request_data(std::size_t bytes) { uint8_t* buf = new uint8_t[bytes]; boost::asio::async_read(socket, boost::asio::buffer(buf, bytes), boost::bind(&Connection::handle_read, shared_from_this(), buf, bytes, boost::asio::placeholders::error)); } void Connection::got_message(const Message::p& msg) { // TODO: Implement message queueing. For now, unexpected messages will cause an error. boost::function f = recv_callback; recv_callback.clear(); error_callback.clear(); f(msg); } void Connection::error(const std::string& msg) { if(error_callback) { boost::function f = error_callback; recv_callback.clear(); error_callback.clear(); f(msg); } else { recv_callback.clear(); } } void Connection::write_data(uint8_t* data, std::size_t bytes) { boost::asio::async_write(socket, boost::asio::buffer(data, bytes), boost::bind(&Connection::handle_write, shared_from_this())); } Connection::p Connection::create(boost::asio::io_service& io_service) { return Connection::p(new Connection(io_service)); } void Connection::recv(boost::function callback, boost::function error) { recv_callback = callback; error_callback = error; start_recv(); }