![](/img/trans.png)
[英]How can I get the amount of transferred bytes on asynchronous reading boost asio c++
[英]What's the meaning of boost::asio::placeholders::bytes_transferred
async_read_until()
的boost::asio::placeholders::bytes_transferred
是什么意思? 在回調函數中,它返回的值小於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 / *的略微修改的示例。
在第二個例子中,我松開整個標題:(
函數有四個重載,但我們只假設使用了第一個。 如果查看文檔 ,那么您將看到bytes_transferred
是指定的分隔符的字節數。
而且:
在成功執行async_read_until操作后,streambuf可能包含分隔符之外的其他數據。 應用程序通常會將該數據保留在streambuf中,以供后續的async_read_until操作進行檢查。
解決。 我從服務器發送回復時,將std::string
對象傳遞給boost::asio::buffer()
,而不是std::string.c_str()
。
正如文檔建議的那樣,您應該能夠忽略bytes_transferred
之外的任何bytes_transferred
並再次調用async_read_until
。
但是,如果你碰巧在ASIO 1.5.3中使用了全新的SSL實現(它還沒有正式升級),你可能會遇到我所做的相同問題(為此我提交了一個補丁):
http://comments.gmane.org/gmane.comp.lib.boost.asio.user/4803
它看起來並不像您正在使用新版本或遇到同樣的問題,但如果您遇到一些限制並且受到新實現的優勢所誘惑,則需要注意這一點:
新實現編譯速度更快,性能顯着提高,並支持自定義內存分配和處理程序調用。 它包括新的API功能,例如證書驗證回調,並改進了錯誤報告。 對於大多數用途,新實現與舊的源代碼兼容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.