diff options
| author | Dennis Brentjes <d.brentjes@gmail.com> | 2016-10-12 14:26:12 +0200 |
|---|---|---|
| committer | Dennis Brentjes <d.brentjes@gmail.com> | 2016-10-12 14:26:12 +0200 |
| commit | 7bca48bc5b5e37a3a8b0b23e57b88d069fa50589 (patch) | |
| tree | 47cd62512e631a064852015c65bb1965bc72414a /libcmix-network/client.hpp | |
| parent | 0fb433690c0ca5f9561fe9e2e973e2cd61b873ba (diff) | |
| download | cmix-7bca48bc5b5e37a3a8b0b23e57b88d069fa50589.tar.gz cmix-7bca48bc5b5e37a3a8b0b23e57b88d069fa50589.tar.bz2 cmix-7bca48bc5b5e37a3a8b0b23e57b88d069fa50589.zip | |
Major network rewrite.
One generic class has been introduced to handle all connection types.
Typedefs provide Sender Receiver and SenderReceiver types, which limit
the functionality of the types. As to not accidentally communicate with
the wrong node about things.
Diffstat (limited to 'libcmix-network/client.hpp')
| -rw-r--r-- | libcmix-network/client.hpp | 37 |
1 files changed, 35 insertions, 2 deletions
diff --git a/libcmix-network/client.hpp b/libcmix-network/client.hpp index dc3787d..7bfea7d 100644 --- a/libcmix-network/client.hpp +++ b/libcmix-network/client.hpp @@ -1,7 +1,13 @@ #pragma once +#include "logging.hpp" + #include <boost/asio/ip/tcp.hpp> #include <boost/asio/streambuf.hpp> +#include <boost/asio/placeholders.hpp> +#include <boost/bind.hpp> +#include <boost/asio/buffer.hpp> +#include <boost/array.hpp> #include <array> @@ -69,17 +75,44 @@ public: */ void async_connect(std::string next_host, std::string next_port, std::function<void()> on_connect); + inline static void foo() {} + /*! * \brief send sends the string prefixed with it's length over the socket. * \param message The string to be sent. */ - void send(std::string message); + template <typename F> + void async_send(std::string message, F on_sent) { + auto length_buffer = prepare_length_prefix(message.size()); + + boost::array<boost::asio::const_buffer, 2> package = { + boost::asio::buffer(length_buffer.data(), length_buffer.size()), + boost::asio::buffer(message) + }; + + auto handler = [on_sent](boost::system::error_code const& ec, std::size_t bytes_transferred) { + if(ec) { + BOOST_LOG_TRIVIAL(fatal) << ec; + throw std::runtime_error("unable to send message"); + } + on_sent(); + }; + + socket.async_send(package, 0, handler); + } /*! * \brief receive * \param message_handler The function to call when a message has been received. */ - void receive(MessageHandler message_handler); + void receive(MessageHandler message_handler) { + using namespace boost::asio::placeholders; + + socket.async_receive( + buffer->prepare(4), + boost::bind(&Client::handle_receive_size, this, message_handler, error(), bytes_transferred()) + ); + } /*! * \brief close Closes the underlying socket. |
