简体   繁体   中英

Receive compressed data using Boost::asio

I have a client that sends me data using this function:

void CServerRetrieve::Send(char *buf, DWORD size, int flags)
{
    unsigned char *zlib;
    unsigned long szzlib;
    m_zlib.Deflate((unsigned char*)buf, size + 1, &zlib, &szzlib); // include the terminating 0 char
    char zbuf[5];
    zbuf[0] = 'Z';
    memcpy(&zbuf[1], &szzlib, 4);
    send(m_Socket, zbuf, 5, flags);
    send(m_Socket, (char*)zlib, szzlib, flags);
    delete [] zlib;
}

I want to receive this data using Boost::asio, however I am not sure what type of buffer I should pass to socket.async_receive in order for it to receive this data?

I have tried a std::vector<char> and std::vector<std::string> , however no data is ever received in my buffer?

Can someone assist me as to what I'm doing wrong?

void tcp_connection::start()
{
    socket_.async_receive(boost::asio::buffer(buff), boost::bind(&tcp_connection::handle_read, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}

void tcp_connection::handle_read(const boost::system::error_code& err, size_t bytes_transferred)
{
    if (!err || err ==  boost::asio::error::message_size)
    {
        size_t sz = buff.size(); //always 0!
    }
}

The fact that you are receiving compressed data really does not matter to Boost.Asio. Assuming you you know the size of the data you are about to receive, a std::vector<char> is fine for receiving the compressed data. You'll need to resize it prior to invoking async_receive Just make sure this buffer does not go out of scope until the completion handler is invoked. This concept is explained int the async_read documentation .

buffers

One or more buffers into which the data will be read. The sum of the buffer sizes indicates the maximum number of bytes to read from the stream. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called .

I'm assuming buff is your std::vector? In that case, before the async_receive you should probably initialize this with the size you intend to read, like

buff.resize(5);

You should also consider using async_read if you know the size of the message you're going to receive. In any case you need to set a size for your buffer.

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