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

Remarks

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

代码参考如下:

void Sign::AfterWriteMessage(error_code const& ec, size_t bytes_transferred, size_t expected_size,  size_t offset) {
  if (ec) {
    BOOSTER_ERROR("AfterWriteMessage") << "write message failed, error code:" << ec.value()
				       << " category name:" << ec.category().name()
				       << " id_:" << id_
				       << " address:" << address  
				       << " message:" << ec.message();
    Close();
    return;
  }

  BOOSTER_DEBUG("AfterWriteMessage") << "thread id: " << this_thread::get_id() << " send_buffer: " << PrintBytesAsHexString(send_buffer, bytes_transferred) << " sent size:" << bytes_transferred;
  BOOSTER_DEBUG("AfterWriteMessage") << "thread id: " << this_thread::get_id() << " send_buffer: " << PrintBytesAsHexString(send_buffer, expected_size) << " expected size:" << expected_size;
  
  size_t resend_size = expected_size - bytes_transferred;
  if (resend_size > 0) {
    size_t new_offset = offset + bytes_transferred;
    async_write(socket, buffer((void*)&send_buffer[new_offset], resend_size),
		strand_.wrap(bind(&Sign::AfterWriteMessage, shared_from_this(), _1, _2, resend_size, new_offset)));
    return;
  }

  // do your business after send succeeds
  
}

void Sign::SendMessage(size_t size) {
  //  BOOSTER_DEBUG("SendMessage") << "thread id: " << this_thread::get_id() << " send_buffer: " << PrintBytesAsHexString(send_buffer, size) << " size:" << size;
  async_write(socket, buffer(send_buffer, size),
	      strand_.wrap(bind(&Sign::AfterWriteMessage, shared_from_this(), _1, _2, size, 0)));
}


但是为什么呢?难道真的是bug. 请看下一篇。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值