jeudi 25 février 2016

boost::udp socket.recieve_from() appends data to the end of the buffer

I have implemented a udp_client using boost_asio The udp_client::recieve_from() is given below.

void udp_client::recieve_from()
{
    for(unsigned int i = 0; i < m_buffer_manager.get_recieve_array().size(); ++i)
        m_buffer_manager.get_recieve_array()[i] = 0;

    /*Initialize our endpoint*/
    size_t len = m_socket.receive_from(
                     boost::asio::buffer(m_buffer_manager.get_recieve_array()), m_sender_endpoint);

    m_buffer_manager.message_buffer(m_buffer_manager.get_recieve_array(),len);
    std::cout << "Length of recieved message " << len << std::endl;
    /*dumps the message into std::cout for debugging.*/
    std::cout << m_buffer_manager.get_message_string() << std::endl;
    //std::cout.write((const char*)&m_buffer_manager.get_recieve_array()[0], len);

    packet_t ack_packet = { "ACK", {} };
    auto buffer = ack_packet.serialize();
    m_socket.send_to(boost::asio::buffer(buffer), m_endpoint);
}

The udp_client.hpp file is shown below.

class udp_client
{
public:
    udp_client(boost::asio::io_service& io_service,const std::string& host,const std::string& port);
    ~udp_client();
    void subscribe();
    void publish(const std::string& message);
    void recieve_from();

private:
    boost::asio::io_service& m_io_service;
    boost::asio::ip::udp::udp::socket m_socket;
    boost::asio::ip::udp::udp::endpoint m_endpoint;
    boost::asio::ip::udp::endpoint m_sender_endpoint;
    buffer_manager m_buffer_manager;
};

The buffer_manager object that is used to manage the recieve buffer is shown below.

class buffer_manager
{
public:
    typedef boost::array<unsigned char, 4096> m_array_type;
    buffer_manager();
    ~buffer_manager();
    void message_buffer(m_array_type &recv_buf,size_t size);
    buffer_manager::m_array_type & get_recieve_array();
    std::string & get_message_string();

private:
    std::string m_message;
    m_array_type m_recv_buf;
};

My problem with the udp_client::recieve_from() code is that

size_t len = m_socket.receive_from(boost::asio::buffer(m_buffer_manager.get_recieve_array()), m_sender_endpoint);

returns 1 packet after recieving one packet. When it recieves two packets it recieves the entire two packets. (i.e the contents of the second packet are appended to the contents of the first packet.)

This is inspite of

for(unsigned int i = 0; i < m_buffer_manager.get_recieve_array().size(); ++i)
            m_buffer_manager.get_recieve_array()[i] = 0;

where I explictly clear the buffer. What is the reason for this? How do I get around this issue.?

Aucun commentaire:

Enregistrer un commentaire