c++ - 使用 Boost::asio 接收压缩数据

标签 c++ sockets boost boost-asio compression

我有一个客户端使用这个函数向我发送数据:

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

我想使用 Boost::asio 接收此数据,但是我不确定我应该将哪种类型的缓冲区传递给 socket.async_receive以便它接收此数据?

我试过 std::vector<char>std::vector<std::string> ,但是我的缓冲区中没有收到任何数据?

有人可以帮助我解决我做错了什么吗?

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

最佳答案

您正在接收压缩数据这一事实对 Boost.Asio 来说真的无关紧要。假设您知道将要接收的数据的大小,std::vector<char>适合接收压缩数据。你需要 resize它在调用之前 async_receive只需确保在调用完成处理程序之前此缓冲区不会超出范围。 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.

关于c++ - 使用 Boost::asio 接收压缩数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4873347/

相关文章:

java - 普通 Java 套接字中没有密码套件

python - 为什么这个程序挂起?

c++ - 将 asio read_some 转换为异步版本

c++ - 加载共享库时出错 : libboost_system. 所以 1.49.0: 没有这样的文件或目录

c++ - boost odeint 什么时候真正调用观察者?

c++ - 结构/类数据对齐和填充算法?

c++ - 用 C++ 编辑/etc/fstab 条目

c++ - QWebEngine如何加载缓存?

c++ - 通过 visual studio 2010 项目模板设置 cocos2d-x 应用程序

spring - SocketInputStream.socketRead0占用应用程序时间的30%