如何将数据写入MutableBufferSequence

时间:2017-09-28 10:39:38

标签: c++ boost boost-asio

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

  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的文档,似乎没有任何明显的方法可以做到这一点。显然我对某些事情产生了极大的误解。

1 个答案:

答案 0 :(得分:3)

我跳过了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