boost::asio async_write也不能保證一次發完所有數據 一


你要是看過basic_stream_socket的文檔,里面提到async_write_some不能保證將所有要發送的數據都發出去。並且提到如果想這樣做,需要使用boost asio的async_write

http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/reference/basic_stream_socket/async_write_some.html

 

[plain]  view plain copy print ?
 
  1. Remarks  
  2.   
  3. The write operation may not transmit all of the data to the peer. Consider using the async_write function if you need to ensure that all data is written before the asynchronous operation completes.  


但是這幾天我就遇到一個問題,以前一直都是一次發送成功的。

 

我想發送54個字節的數據,可是每次都是只發9個字節。因此只好自己寫了一個重試發送的遞歸函數。也很簡單,通過bind,每次傳遞想要發送的字節數木和發送開始位置給異步回調函數。

代碼參考如下:

 

[cpp]  view plain copy print ?
 
  1. void Sign::AfterWriteMessage(error_code const& ec, size_t bytes_transferred, size_t expected_size,  size_t offset) {  
  2.   if (ec) {  
  3.     BOOSTER_ERROR("AfterWriteMessage") << "write message failed, error code:" << ec.value()  
  4.                        << " category name:" << ec.category().name()  
  5.                        << " id_:" << id_  
  6.                        << " address:" << address    
  7.                        << " message:" << ec.message();  
  8.     Close();  
  9.     return;  
  10.   }  
  11.   
  12.   BOOSTER_DEBUG("AfterWriteMessage") << "thread id: " << this_thread::get_id() << " send_buffer: " << PrintBytesAsHexString(send_buffer, bytes_transferred) << " sent size:" << bytes_transferred;  
  13.   BOOSTER_DEBUG("AfterWriteMessage") << "thread id: " << this_thread::get_id() << " send_buffer: " << PrintBytesAsHexString(send_buffer, expected_size) << " expected size:" << expected_size;  
  14.     
  15.   size_t resend_size = expected_size - bytes_transferred;  
  16.   if (resend_size > 0) {  
  17.     size_t new_offset = offset + bytes_transferred;  
  18.     async_write(socket, buffer((void*)&send_buffer[new_offset], resend_size),  
  19.         strand_.wrap(bind(&Sign::AfterWriteMessage, shared_from_this(), _1, _2, resend_size, new_offset)));  
  20.     return;  
  21.   }  
  22.   
  23.   // do your business after send succeeds  
  24.     
  25. }  
  26.   
  27. void Sign::SendMessage(size_t size) {  
  28.   //  BOOSTER_DEBUG("SendMessage") << "thread id: " << this_thread::get_id() << " send_buffer: " << PrintBytesAsHexString(send_buffer, size) << " size:" << size;  
  29.   async_write(socket, buffer(send_buffer, size),  
  30.           strand_.wrap(bind(&Sign::AfterWriteMessage, shared_from_this(), _1, _2, size, 0)));  
  31. }  

 

但是為什么呢?難道真的是bug. 請看下一篇。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM