reworked message's receive interface

This commit is contained in:
Kjistóf 2016-11-20 00:18:14 +01:00
parent 5d124db96e
commit 41f81518c2
4 changed files with 30 additions and 31 deletions

View File

@ -15,5 +15,27 @@ void message::send(boost::asio::ip::tcp::socket& socket)
throw std::runtime_error("Networking error: " + ec.message());
}
void 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());
process_data(data);
}
message::~message() {}

View File

@ -9,11 +9,12 @@ class message
protected:
virtual std::string get_message_length() = 0;
virtual std::string get_message() = 0;
virtual void process_data(std::string&) = 0;
public:
void send(boost::asio::ip::tcp::socket&);
virtual void receive(boost::asio::ip::tcp::socket&) = 0;
void receive(boost::asio::ip::tcp::socket&);
virtual ~message();
};

View File

@ -7,8 +7,7 @@ using namespace boost;
text_message::text_message() {}
text_message::text_message(std::string text):_text(text)
{}
text_message::text_message(std::string text):_text(text) {}
std::string text_message::get_text()
@ -23,33 +22,11 @@ std::string text_message::get_message_length()
std::string text_message::get_message()
{
return _text;
}
{ return _text; }
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;
}
void text_message::process_data(std::string& string)
{ _text = string; }
text_message::~text_message()
{}
text_message::~text_message() {}

View File

@ -14,6 +14,7 @@ private:
protected:
virtual std::string get_message_length() override;
virtual std::string get_message() override;
virtual void process_data(std::string&) override;
public:
text_message();
@ -21,7 +22,5 @@ public:
std::string get_text();
virtual void receive(boost::asio::ip::tcp::socket&) override;
virtual ~text_message() override;
};