boost :: asio :: udp异步响应未完全收到

时间:2018-01-20 14:17:16

标签: c++ udp boost-asio packet datagram

解释

我的程序将udp数据报发送到服务器。使用wireshark我看到了查询和服务器的响应(79字节)。

发送功能

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;
}

开始接收功能

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));
}

接收处理程序

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;
    }
}

控制台输出

Bytes transferred 79
11

bytes_transferred值正确但我的响应缓冲区(char vector)&#34; receiveBuffer&#34;仅包含11个字节而不是79个字节。

的Wireshark

发送

Wireshark sending datagram

响应

Wireshark receiving datagram

1 个答案:

答案 0 :(得分:2)

您的问题是strlen((char*)this->receiveBuffer.data())

strlen接受以空字符结尾的C字符串作为输入。所以它在遇到字节00时停止计数。

您似乎收到混合的二进制/文本数据。你不能简单地将它作为一个字符串打印出来。