cpp11chat/message.cpp

41 lines
937 B
C++
Raw Normal View History

#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() + get_message()), ec);
if (ec)
throw std::runtime_error("Networking error: " + ec.message());
}
2016-11-19 23:18:14 +00:00
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();
data.reserve(len);
2016-11-19 23:18:14 +00:00
is.clear();
data = std::string(std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>());
2016-11-19 23:18:14 +00:00
if (ec)
throw std::runtime_error("Networking error: " + ec.message());
process_data(data);
}
message::~message() {}