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

  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,每次传递想要发送的字节数木和发送开始位置给异步回调函数。

代码参考如下:

  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. 请看下一篇。

原文地址:https://www.cnblogs.com/lidabo/p/3799280.html