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中間件 條碼系統中間層 物聯網軟件集成