diff options
author | Vegard Storheil Eriksen <zyp@jvnv.net> | 2010-12-25 12:54:59 +0100 |
---|---|---|
committer | Vegard Storheil Eriksen <zyp@jvnv.net> | 2010-12-25 12:54:59 +0100 |
commit | fae209a9e93400c3a2072befda9c820634cf9278 (patch) | |
tree | 2d69e2c75fff0e08468c168f773abbc939a2ff03 /src/connection.cpp | |
parent | 94a1189d757f0269ac081ad2d750152e30564986 (diff) |
Diffstat (limited to 'src/connection.cpp')
-rw-r--r-- | src/connection.cpp | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/src/connection.cpp b/src/connection.cpp new file mode 100644 index 0000000..1e38f7b --- /dev/null +++ b/src/connection.cpp @@ -0,0 +1,67 @@ +#include "connection.h" + +#include <boost/bind.hpp> + +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<void (Message::p)> f = recv_callback; + recv_callback.clear(); + error_callback.clear(); + + f(msg); +} + +void Connection::error(const std::string& msg) { + if(error_callback) { + boost::function<void (const std::string&)> 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<void (Message::p)> callback, boost::function<void (const std::string&)> error) { + recv_callback = callback; + error_callback = error; + + start_recv(); +}
\ No newline at end of file |