Search code examples
boostudpboost-asio

How to Read data from boost UDP server


This is the code for the UDP server which receives data and prints it.

I am able to receive the message but in the end of the message i get some junk characters also.

I only want to display the actual message sent without the junk chars in the end.

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#pragma once

#include <string>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/array.hpp>
#include <qdebug.h>


using boost::asio::ip::udp;

class udp_server
{
public:

    udp_server(boost::asio::io_service& io_service)
        : socket_(io_service, udp::endpoint(udp::v4(), 13))
    {
        start_receive();
    }

private:

    void start_receive()
    {
        socket_.async_receive_from(
            boost::asio::buffer(recv_buffer_), remote_endpoint_,
            boost::bind(&udp_server::handle_receive, this,
                boost::asio::placeholders::error,
                boost::asio::placeholders::bytes_transferred));
    }

    void handle_receive(const boost::system::error_code& error,
        std::size_t /*bytes_transferred*/)
    {

        if (!error || error == boost::asio::error::message_size)
        {

            std::string str(recv_buffer_.c_array());
            std::cout << str; // Printing the string shows junk characters also
            boost::shared_ptr<std::string> message(
                new std::string("WAVEFRONT"));

            socket_.async_send_to(boost::asio::buffer(*message), remote_endpoint_,
                boost::bind(&udp_server::handle_send, this, message,
                    boost::asio::placeholders::error,
                    boost::asio::placeholders::bytes_transferred));

            start_receive();

        }
    }


    void handle_send(boost::shared_ptr<std::string> /*message*/,
        const boost::system::error_code& /*error*/,
        std::size_t /*bytes_transferred*/)
    {
    }

    
    udp::socket socket_;
    udp::endpoint remote_endpoint_;
    boost::array< char, 256> recv_buffer_;
};

Solution

  • "the junk chars in the end" are the chars in your recv_buffer_ after the UDP data that asio received.

    The bytes_transferred parameter that you have commented out of the handle_receive function tells you how many chars asio actually received, which is <= recv_buffer_.size().

    If you just copy bytes_transferred chars to str, you will see what was received without "the junk chars in the end".