I use boost::asio for asynchronous client and server. In working process a client send to server data of different type: small service messages (5-50 B) and largest messages (40-200 KB) with raw image data. When I call Client::send in order (in one thread, successively):
- send "small service message";
- send "large image message";
I get mixed data (wrong) on the server lake as:
|begin of large message||small message||end of large message|
void Client::send(MessageType type, const void* data, int size, bool read_header_after) {
assert(cstatus.is_connected());
header.type = type;
size_t buf_size = sizeof(ProtocolHeader) + size;
Bytes *p = new Bytes();
p->resize(buf_size);
std::memcpy(&p->front(), &header, sizeof(ProtocolHeader));
if (size) {
std::memcpy(&p->at(sizeof(ProtocolHeader)), data, size);
}
std::cout << "***** SEND start: " << p->size() << " bytes *****" << std::endl;
ba::async_write(*socket, ba::buffer(&p->front(), buf_size),
ba::transfer_exactly(buf_size),
[this, p, read_header_after](const boost::system::error_code& ec, std::size_t length) {
std::cout << "***** SEND complete: "
<< p->size() << " bytes; ec="
<< ec.value() << " (" << ec.message() << ") bufsize="
<< p->size()
<< " *****"
<< std::endl;
size_t buf_size = p->size();
delete p; // remove sent data
if (ec) {
cstatus.set_last_network_error("Client::send " + ec.message());
connection_failed("send - ec");
} else if (length < buf_size) {
connection_failed("send - len");
} else {
if (read_header_after) {
read_header();
}
start_check_timer(NORMAL_INTERVAL_DATA_SEND_MILLISEC);
}
});
}
Output show that small message send to async_write as second but executed (finished) as the first before large message.
***** SEND start: 53147 bytes *****
***** SEND start: 5 bytes *****
***** SEND complete: 5 bytes; ec=0 (Success) bufsize=5 *****
***** SEND complete: 53147 bytes; ec=0 (Success) bufsize=53147 *****
How it possible and how sync this? Thanks!
Update
I don't need queue of sync tasks. I need sync two async_write operations with different buffers sizes.