1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
// Lecture asynchrone de données depuis le socket
template <typename T, typename Handler>
void async_read(T& t, Handler handler)
{
boost::asio::async_read(m_socket, boost::asio::buffer(m_inbound_header),
boost::bind(&tcp_connection::handle_read_header<T, Handler>,
this, boost::asio::placeholders::error, boost::ref(t), handler));
}
//Interprétation du header
template <typename T, typename Handler>
void handle_read_header(const boost::system::error_code& e, T& t, Handler handler)
{
if (e)
{
handler(e);
}
else
{
// Détermine la longueur du vrai message (11)
std::istringstream is(std::string(m_inbound_header, header_length));
std::size_t m_inbound_datasize = 0;
if (!(is >> std::hex >> m_inbound_datasize))
{
// Header non valide, on informe la fonction appelante
boost::system::error_code error(boost::asio::error::invalid_argument);
handler(error);
return;
}
// On récupère les données (12)
m_inbound_data.resize(m_inbound_datasize);
boost::asio::async_read(m_socket, boost::asio::buffer(m_inbound_data),
boost::bind(&tcp_connection::handle_read_data<T, Handler>, this,
boost::asio::placeholders::error, boost::ref(t), handler));
}
}
// Les données reçues, on les désérialise (13)
template <typename T, typename Handler>
void handle_read_data(const boost::system::error_code& e,
T& t, Handler handler)
{
if (e)
{
handler(e);
}
else
{
// On extrait (14)
try
{
std::string archive_data(&m_inbound_data[0], m_inbound_data.size());
std::istringstream archive_stream(archive_data);
boost::archive::text_iarchive archive(archive_stream);
archive >> t;
}
catch (std::exception&)
{
// En cas d'échec
boost::system::error_code error(boost::asio::error::invalid_argument);
handler(error);
return;
}
// On informe l'appelant que tout s'est bien passé. (15)
handler(e);
}
} |
Partager