简体   繁体   中英

boost::asio::udp async response is not entirely received

Explanation

My program sends an udp datagram to a server. Using wireshark I see the query and the response from the server (79 Bytes).

Send function

void Query::start_send(const std::string data, const QueryType queryType) {
    boost::shared_ptr<std::string> message(new std::string(data));
    socket.async_send_to(boost::asio::buffer(*message), endPoint,
        boost::bind(&Query::handler_send, this, message,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));
    this->queryType = queryType;
}

Start receive function

void Query::start_receive() {
    socket.async_receive_from(
        boost::asio::buffer(receiveBuffer, receiveBuffer.max_size()), endPoint,
        boost::bind(&Query::handler_receive, this,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));
}

Receive handler

void Query::handler_receive(const boost::system::error_code& error, std::size_t bytes_transferred)
{
    if (!error || error == boost::asio::error::message_size) {
        std::cout << "Bytes transferred " << bytes_transferred << std::endl << strlen((char*)this->receiveBuffer.data()) << std::endl;
    }
    else {
        std::cout << "Receive failed" << std::endl << error.value() << std::endl << error.message() << std::endl;
    }
}

Console output

Bytes transferred 79
11

The bytes_transferred value is correct but my response buffer (char vector) "receiveBuffer" contains only 11 Bytes instead of 79 Bytes.

Wireshark

Sending

Wireshark发送数据报

Response

Wireshark接收数据报

Your issue is with strlen((char*)this->receiveBuffer.data()) .

strlen accepts a nul-terminated C-string as input. So it stops counting when it encounters the byte 00 .

You seem to receive mixed binary/text data. You can't simply print it out as a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM