2011-06-20 62 views
3

boost::asio::placeholders::bytes_transferredasync_read_until()中是什么意思?在回调函数中,它会返回比streambuf.size()更小的值。在回调之前,streambuf已经清楚。综上所述,... bytes_transferred不是实际通过套接字的字节数,而是更少。我是否误解了所有这些,或者是什么?boost :: asio ::占位符:: 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 /示例/ SSL/*例子。

在第二个例子中,我失去了整个头部:(

回答

3

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

比你们都!

4

有功能四个重载,但我们只是假设第一个被使用。如果你看一下documentation,然后你会看到bytes_transferred是。字节的数量和包括指定的分隔

进而:

成功async_read_until操作之后,流缓冲可以包含附加数据以外的定界符的应用程序通常将离开。 streambuf中的数据用于随后的async_read_until操作进行检查。

0

正如文档所示,您应该能够忽略bytes_transferred之外的任何内容,并且只需再次调用async_read_until即可。但是如果你碰巧在ASIO 1.5.3中使用了全新的SSL实现(这还没有正式成为boost的一部分),那么你可能遇到同样的问题(我提交了一个补丁) :

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

它看起来并不像你所使用的新版本或运行到同样的问题,但它的东西要知道,如果你击出了一些限制和的优势被诱惑新实现:

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

+0

感谢您的回复,但我认为我遇到了其他问题。 有时,直到第一个分隔符为止的缓冲区内容被清零,所以我有效地丢失了数据包的标题。不过,这是随机行为。 –