我有一个客户端使用这个函数向我发送数据:
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/