4

有没有办法在不删除字节的情况下从流缓冲区中读取?

我正在从缓冲区中读取“消息大小”字段以检查是否收到了整个消息。

如果不是,我将发布另一个异步读取来获取它,但是处理程序无法知道消息应该持续多长时间 - 因为 size 字段已被删除。

任何帮助表示赞赏!

例如

boost::asio::streambuf _buffer;

void onReceive(const boost::system::error_code& e, std::size_t bytesTransferred)
{
  if(e) return;

  if(_buffer.size() > 0)
  {
    // Partial message was previously received, but I don't know how long.
  }
  else
  {
    _buffer.commit(bytesTransferred);

    /* Read the size (and remove it from the stream) */
    unsigned short size = 0;
    std::istream in(&_buffer);
    in.read((char*)&size, sizeof(unsigned short);

    /* Got the whole message? */
    if(_buffer.size() > size)
    {
      /* Yes. */
    }
    else
    {
      /* No - read the rest. */
      boost::asio::async_read(/*...*/);
    }
  }
}
4

3 回答 3

2

您可以使用 read_async 使用消息头的大小启动读取,然后在“完成条件”回调中调整它,如下所示:

typedef boost::system::error_code error_code;

template <typename Stream, typename Message>
void MessageReader<Stream, Message>::startRead()
{
  readBuffer = allocateMsg();
  async_read(stream, 
             boost::asio::buffer(readBuffer.get(), sizeof(*readBuffer)),
             boost::bind(&MessageReader<Stream, Message>::bytesToRead, this,
                         boost::asio::placeholders::error, 
                         boost::asio::placeholders::bytes_transferred),
             boost::bind(&MessageReader<Stream, Message>::readDone, this, 
                         boost::asio::placeholders::error, 
                         boost::asio::placeholders::bytes_transferred));
}

template <typename Stream, typename Message>
size_t MessageReader<Stream, Message>::bytesToRead(const error_code& error, 
                                                   size_t bytes_read)
{
  size_t result;

  if (error)
    result = 0;                                         // error - stop reading

  else if (bytes_read < sizeof(CmnMessageHeader))
    result = sizeof(CmnMessageHeader) - bytes_read;     // read rest of header

  else if (readBuffer->header.byteCount > sizeof(*readBuffer))
    result = 0;                                         // bad byte count

  else
    result = readBuffer->header.byteCount - bytes_read; // read message body

  return result;
}

template <typename Stream, typename Message>
void MessageReader<Stream, Message>::readDone(const error_code& error, 
                                              size_t bytes_read)
{
  if (error)
  {
    if (error.value() == boost::system::errc::no_such_file_or_directory)
    {
      notifyStop();
    }

    else if (error.value() != boost::system::errc::operation_canceled)
    {
      notifyStop();
    }

    // else the operation was cancelled, thus no stop notification is needed and
    // we can merely return
  }

  else if (bytes_read != readBuffer->header.byteCount)
  {
    LOG4CXX_ERROR(logger, "Message byte count mismatch");
    notifyStop();
  }

  else
  {
    handleMsg(readBuffer);
    startRead();
  }
}

编辑:为 error_code 添加了 typedef。

于 2012-02-05T04:03:09.900 回答
2

我昨天做了这个。所以我想我会提供我的解决方案......

#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>

#include <boost/asio.hpp>
#include <boost/asio/streambuf.hpp>

void ReadFromStreambuf()
{
    boost::asio::streambuf mybuffer;

    // write some data to the buffer
    std::ostream o2buffer (&mybuffer);
    o2buffer << "hello stackoverflow";

    // get buffer size
    size_t nBufferSize = boost::asio::buffer_size(mybuffer.data());

    // get const buffer
    std::stringstream ssOut;
    boost::asio::streambuf::const_buffers_type constBuffer = mybuffer.data();

    // copy const buffer to stringstream, then output
    std::copy(
        boost::asio::buffers_begin(constBuffer),
        boost::asio::buffers_begin(constBuffer) + nBufferSize,
        std::ostream_iterator<char>(ssOut)
    );

    std::cout << ssOut.str() << "\n";
}


int main(int argc, char const *argv[])
{
    ReadFromStreambuf();
    return 0;
}
于 2017-06-23T06:51:12.247 回答
0

您可以采用两种方法:

  1. 发出一次读取以读取大小的字节数(例如 4),发出所需大小的读取。

  2. 使用 read some 调用,并缓冲代码中的字节,例如在向量中并以这种方式进行分析。

我会选择选项 2,它确实意味着复制缓冲区,但是我会冒险它比多次读取一些调用便宜。

于 2012-02-05T00:02:38.557 回答