---
title: "恼人的boost::asio::async_read_until"
author: "byytj"
date: "2012-12-27T23:21:07Z"
tags: []
categories: ["编程语言"]
slug: "boost-asio-async-read-until"
draft: false
lastmod: "2012-12-28T00:31:09Z"
id: 1756093
url: "https://byytj.iteye.com/blog/1756093"
---

恼人的boost::asio::async\_read\_until

2012-12-04 10:09:51     [我来说两句](/admin/blogs/#comment_iframe)      

[收藏]()    [![](http://www.2cto.com/statics/images/dl.jpg)我要投稿](http://www.2cto.com/index.php?m=member&c=content&a=publish&modid=1&siteid=1)

最近为服务器添加XMLSocket与Flash进行通信, 这种协议其实是一种以\\0结尾的字符串协议, 为了让asio兼容此协议, 我从文档找到了async\_read\_until异步读取系列, 这个函数的原理时, 给定一个streambuf, 和一个分隔符, asio碰到分隔符时返回, 你可以从streambuf中读取需要的数据. 看似很简单, 我很快写好一个demo与Flash进行通信, 结果发现在一个echo逻辑速度很快时, 服务器居然乱包了, 网上查了下, 官方原文是这样的:

”After a successful async\_read\_until operation, the streambuf may contain additional data beyond the delimiter. An application will typically leave that data in the streambuf for a subsequent async\_read\_until operation to examine.”

意思是, streambuf中并不一定是到分隔符前的所有数据, 多余的数据可能一样会在streambuf中. 也就是说, 还需要自己再次处理一遍数据...

动手呗, async\_read\_until看似就是一个废柴, 底层已经费了很多CPU在逐字符与分隔符的匹配上, 抛上来的数据居然还是半成品.

代码如下, 测试通过, 但是实在很费解为啥非要再做一次..

          boost::asio::streambuf* SB = SBP.get();

            // 访问缓冲  
            const char* Buffs = boost::asio::buffer\_cast&lt;const char\*&gt;( SB-&gt;data() );

            uint32 DataSize = 0;  
            for ( uint32 i = 0; i &lt; SB-&gt;size(); ++i )  
            {  
                const char DChar = Buffs\[i];

                // 这里需要自己判断字符串内容, read\_until的文档里这么说的  
                if ( DChar == '\\0' )  
                {  
                    DataSize = i;  
                    break;  
                }  
            }

            if ( DataSize &gt; 0 )  
            {  
                // 取成字符串  
                std::string FullText( Buffs, DataSize );  
                 
                // 消费  
                SB-&gt;consume( DataSize );               

                mWorkService-&gt;post(  
                    boost::bind(&AsioSession::NotifyReadString,  
                    shared\_from\_this(),  
                    FullText )  
                    );

            } [www.2cto.com](http://www.2cto.com/)  
  另外, 为了保证输入性安全, 可以在streambuf构造时加一个最大一个读取量, 超过此量会返回报错, 避免了缓冲区被撑爆的危险

 [http://www.cppblog.com/sunicdavy/archive/2012/12/03/195921.html](http://www.cppblog.com/sunicdavy/archive/2012/12/03/195921.html)

[http://www.boost.org/doc/libs/1\_43\_0/doc/html/boost\_asio/reference/async\_read\_until/overload1.html](http://www.boost.org/doc/libs/1_43_0/doc/html/boost_asio/reference/async_read_until/overload1.html)