summaryrefslogtreecommitdiff
path: root/src/connection.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/connection.cpp')
-rw-r--r--src/connection.cpp67
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