diff --git a/message.cpp b/message.cpp index 39edd00..a8b9190 100644 --- a/message.cpp +++ b/message.cpp @@ -1,8 +1,20 @@ #include "message.h" +using namespace boost; +void message::send(boost::asio::ip::tcp::socket& socket) +{ + system::error_code ec; + + asio::write(socket, asio::buffer(get_message_length()), ec); + asio::write(socket, asio::buffer(":", sizeof(char)), ec); + asio::write(socket, asio::buffer(get_message()), ec); + + if (ec) + throw std::runtime_error("Networking error: " + ec.message()); +} message::~message() {} \ No newline at end of file diff --git a/message.h b/message.h index 98e1b52..8fd69e7 100644 --- a/message.h +++ b/message.h @@ -6,8 +6,13 @@ class message { +protected: + virtual std::string get_message_length() = 0; + virtual std::string get_message() = 0; + public: - virtual void send(boost::asio::ip::tcp::socket&) = 0; + + void send(boost::asio::ip::tcp::socket&); virtual void receive(boost::asio::ip::tcp::socket&) = 0; virtual ~message(); diff --git a/text_message.cpp b/text_message.cpp index 7b74624..3017360 100644 --- a/text_message.cpp +++ b/text_message.cpp @@ -11,19 +11,15 @@ text_message::text_message(std::string text):_text(text) {} -void text_message::send(boost::asio::ip::tcp::socket& socket) +std::string text_message::get_message_length() { - boost::system::error_code ec; + return std::to_string(_text.size()); +} - asio::write(socket, asio::buffer(std::to_string(_text.size())), ec); - - asio::write(socket, asio::buffer(":", sizeof(char)), ec); - - asio::write(socket, asio::buffer(_text), ec); - - if (ec) - throw std::runtime_error("Networking error: " + ec.message()); +std::string text_message::get_message() +{ + return _text; } diff --git a/text_message.h b/text_message.h index 56389f3..19b96a9 100644 --- a/text_message.h +++ b/text_message.h @@ -10,11 +10,14 @@ class text_message : public message private: std::string _text; +protected: + virtual std::string get_message_length() override; + virtual std::string get_message() override; + public: text_message(); text_message(std::string); - virtual void send(boost::asio::ip::tcp::socket&) override; virtual void receive(boost::asio::ip::tcp::socket&) override; virtual ~text_message() override;