boost :: asio :: placeholders :: bytes_transferred的含义是什么?

时间:2011-06-20 13:17:17

标签: c++ boost boost-asio

boost::asio::placeholders::bytes_transferredasync_read_until()的含义是什么?在回调函数中,它返回的值小于streambuf.size()。在回调之前streambuf很清楚。总而言之,...... bytes_transferred不是通过套接字的实际字节数,而是更少。我是否误解了所有这些,或者是什么?

编辑:我从套接字中读取了以下协议:

  

Y43,72,0,,91009802000000603=0000000000000000000

"Y43," - 是标题 "Y" - 是消息类型。
"43" - 要读取的额外字节数 "," - 分隔符。标题是直到第一个“,”遇到。

我的代码用于阅读就像:

void handle_write(const boost::system::error_code& error,
                  size_t bytes_transferred)
{
    if (!error)
    {
        boost::asio::async_read_until(
            socket_,
            inputStreamBuffer_,
            ',',
            boost::bind(
                &client::handle_read1, this,
                boost::asio::placeholders::error,
                boost::asio::placeholders::bytes_transferred
            )
        );
    }
    else
    {
        std::cout << "Write failed: " << error << "\n";
    }
}

void handle_read1(const boost::system::error_code& error,
                  size_t bytes_transferred)
{
    cout << "bytes_transferred=" << bytes_transferred << endl;

    if (!error)
    {
        cout << "0 size=" << inputStreamBuffer_.size() << endl;
        istream is(&inputStreamBuffer_);
        char c[1000];
        is.read(c,bytes_transferred);
        c[bytes_transferred]=0;
        for (int i=0;i<bytes_transferred;++i)
        {
            cout << dec << "c[" << i << "]=" << c[i] << " hex=" << hex << static_cast<int>(c[i]) << "#" << endl;
        }
    }
    else
    {
        std::cout << "Read failed: " << error << "\n";
    }
}

对于从另一方发送的流:

  

Y43,71,0,,91009802000000595=0000000000000000000

有时,我读到了这个:

  

bytes_transferred=4
  0 size=47
  c[0]=Y hex=59#
  c[1]=4 hex=34#
  c[2]=3 hex=33#
  c[3]=, hex=2c#

对于从另一方发送的流:

  

Y43,72,0,,91009802000000603=0000000000000000000

但其他时候,我读到了这个:

  

bytes_transferred=7
  0 size=47
  c[0]= hex=0#
  c[1]= hex=0#
  c[2]= hex=0#
  c[3]= hex=0#
  c[4]=7 hex=37#
  c[5]=2 hex=32#
  c[6]=, hex=2c#

套接字使用SSL进行保护,客户端和服务器应用程序是boost_asio / example / ssl / *中略有修改的示例。

在第二个例子中,我松开整个标题:(

3 个答案:

答案 0 :(得分:4)

该函数有四个重载,但我们假设使用了第一个。如果你查看documentation,那么你会看到bytes_transferred是包含指定分隔符的字节数。

而且:

  

成功执行async_read_until操作后,streambuf可能包含分隔符之外的其他数据。应用程序通常会将该数据留在streambuf中,以便后续的async_read_until操作进行检查。

答案 1 :(得分:3)

解决。我从服务器发送回复时将std::string对象传递给boost::asio::buffer(),而不是std::string.c_str()

答案 2 :(得分:0)

正如文档所示,您应该可以忽略bytes_transferred之外的任何内容,只需再次致电async_read_until

但是,如果你碰巧在ASIO 1.5.3中使用了全新的SSL实现(它还没有正式升级),你可能会遇到我所做的相同问题(为此我提交了一个补丁):

http://comments.gmane.org/gmane.comp.lib.boost.asio.user/4803

看起来你似乎没有使用新版本或遇到同样的问题,但是如果你遇到一些限制并且受到新实现的优势的诱惑,那就要注意了:

  

新实现编译速度更快,性能显着提高,并支持自定义内存分配和处理程序调用。它包括新的API功能,例如证书验证回调,并改进了错误报告。对于大多数用途,新的实现与源代码兼容。