From 5d124db96e80865b5a11f6ac3bc2eed8adea1c38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kjist=C3=B3f?= Date: Sat, 19 Nov 2016 23:52:43 +0100 Subject: [PATCH] simplified protocol and implemented text_message::receive() --- message.cpp | 1 - text_message.cpp | 28 ++++++++++++++++++++++++++-- text_message.h | 3 +++ 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/message.cpp b/message.cpp index a8b9190..f1bb8d0 100644 --- a/message.cpp +++ b/message.cpp @@ -9,7 +9,6 @@ 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) diff --git a/text_message.cpp b/text_message.cpp index 3017360..4489c79 100644 --- a/text_message.cpp +++ b/text_message.cpp @@ -11,9 +11,14 @@ text_message::text_message(std::string text):_text(text) {} +std::string text_message::get_text() +{ return _text; } + + std::string text_message::get_message_length() { - return std::to_string(_text.size()); + auto sizetext = std::to_string(_text.size()); + return std::string(sizeof(size_t) - sizetext.size(), '0').append(sizetext); } @@ -24,7 +29,26 @@ std::string text_message::get_message() void text_message::receive(boost::asio::ip::tcp::socket& socket) -{} +{ + system::error_code ec; + asio::streambuf sb; + std::istream is(&sb); + std::string data; + + asio::read(socket, sb, asio::transfer_exactly(sizeof(size_t)), ec); + is >> data; + size_t len = std::stoull(data); + + asio::read(socket, sb, asio::transfer_exactly(len), ec); + data.clear(); + is.clear(); + is >> data; + + if (ec) + throw std::runtime_error("Networking error: " + ec.message()); + + _text = data; +} text_message::~text_message() diff --git a/text_message.h b/text_message.h index 19b96a9..1bfc027 100644 --- a/text_message.h +++ b/text_message.h @@ -2,6 +2,7 @@ #include "message.h" #include +#include @@ -18,6 +19,8 @@ public: text_message(); text_message(std::string); + std::string get_text(); + virtual void receive(boost::asio::ip::tcp::socket&) override; virtual ~text_message() override;