boost::asio async_write也不能保证一次发完所有数据 一
睿丰德科技 专注RFID识别技术和条码识别技术与管理软件的集成项目。质量追溯系统、MES系统、金蝶与条码系统对接、用友与条码系统对接
你要是看过basic_stream_socket的文档,里面提到async_write_some不能保证将所有要发送的数据都发出去。并且提到如果想这样做,需要使用boost asio的async_write
[plain] view plaincopyprint?
- 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,每次传递想要发送的字节数木和发送开始位置给异步回调函数。
代码参考如下:
[cpp] view plaincopyprint?
- 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. 请看下一篇。
RFID管理系统集成商 RFID中间件 条码系统中间层 物联网软件集成