c++ - 使用 istream 从 boost basic_streambuf 读取时出现问题

标签 c++ boost boost-asio

我在读取通过 asyc_read() 填充的 streambuf 时遇到了一些问题。在 VS 中单步执行我的代码时,我可以看到缓冲区中有正确的数据,但是当我去读取它时:

std::istream is = std::istream(&buffer_);

unsigned short type;
unsigned short size;

is >> type;
is >> size;

type 和 size 变量保持在它们的初始值。没有错误或任何东西被抛出。我真的很困惑为什么会这样我已经看到类似的代码以完全相同的方式将数据读入变量

编辑: 所以这是我的 async_read 代码,然后调用上面的代码:

boost::asio::async_read(socket_,
    buffer_,
    boost::asio::transfer_at_least(4),
    boost::bind(&Session::handleReadBody, this,
    boost::asio::placeholders::error,
    boost::asio::placeholders::bytes_transferred));

最佳答案

如果 type 保持其初始值,则很明显 是 >> 类型; 失败:检查流的状态 (if(is) { ...) 可以肯定。

并且,鉴于您有一个 transfer_at_least(4),我怀疑您正在传输二进制数据,而不是以空格分隔的 ASCII 字符串。如果是这种情况,请使用 read():

int16_t type, size;
data.read(reinterpret_cast<char*>(&type), sizeof type);
data.read(reinterpret_cast<char*>(&size), sizeof size);

但要注意字节顺序。

关于c++ - 使用 istream 从 boost basic_streambuf 读取时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7397019/

相关文章:

c++ - 插入后列表开始迭代器的有效性

c++ - 为什么在 C++ 中使用 boost multi_array 索引类型来索引 boost 数组?

c++ - boost shared_ptr 和内存分配不起作用

boost-asio - boost.asio,如何使用asio读取一个完整的IP包

c++ - 混合 C 和 C++ 文件操作

c++ - 在 C++ 中传递 C 字符串的问题

c++ - Boost序列化不适用于shared_ptr <int>

c++ - Boost 图形库多态捆绑属性

c++ - Boost :asio? 的最佳文档

multithreading - 多线程boost-asio服务器(vs boost异步服务器教程)