我正在尝试实现一个从std::cin读取的AsyncReadStream流,到目前为止,它具有以下代码:

  template <class MutableBufferSequence, class ReadHandler>
  void async_read_some(const MutableBufferSequence &buf, ReadHandler handler) {

    char c[1024] = {};
    std::streamsize num = std::cin.readsome(c, 1023);
    c[num] = 0;

    boost::asio::streambuf buff(1023);
    std::ostream os(&buff);
    os << c;

    // How do I get the buff into the buf???? I've tried below:
    //boost::asio::buffered_stream<boost::asio::streambuf> buff_stream(buff);
    //boost::asio::read(buff_stream, buf);
    handler(boost::system::error_code(), boost::asio::buffer_size(buf));
  }

我知道上面的一些代码本来应该是阻塞的,但实际上这不是我的问题(我认为)。我已经查看了MutableBufferSequence http://www.boost.org/doc/libs/1_41_0/doc/html/boost_asio/reference/MutableBufferSequence.html的文档,似乎没有任何明显的方法可以做到这一点。显然,我对某些事情有严重的误解。

最佳答案

我会跳过streambuf(为什么要复制两次?)。

template <class MutableBufferSequence, class ReadHandler>
void my_read_some(MutableBufferSequence buf, ReadHandler handler) {

    char tmp[1024] = {};

    std::cin.read(tmp, sizeof(tmp));
    std::streamsize num = std::cin.gcount();

    if(std::cin || num) {
        ba::buffer_copy(buf, ba::buffer(tmp, num));

        handler({}, num);
    } else {
        handler(ba::error::eof, num);
    }
}

(ba::缩写boost::asio::)。

还要注意,read_some可能不是您想要的(std::cin.readsome always reading 0 bytes)。

要使用它:
int main() {
    std::array<char, 512> block1{}, block2{};
    std::vector<ba::mutable_buffers_1> blocks { ba::buffer(block1), ba::buffer(block2) };

    auto handler = [&blocks](boost::system::error_code ec, size_t transferred) {
        if (ec)
            std::cout << "Error " << ec.message() << "\n";
        else {
            std::cout << "Received " << transferred << " bytes\n-------\n";

            std::copy_n(ba::buffers_begin(blocks), transferred, std::ostreambuf_iterator<char>(std::cout));
            std::cout << "\n-------\n";
        }
    };

    my_read_some(blocks, handler);
}

看到它 Live On Coliru

关于c++ - 如何将数据写入MutableBufferSequence,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46467064/

10-11 18:01