Trying to understand boost asio library, I implemented an async echo server. I ask the tcp::socket to do an async_read_some for a small amount of data, namely 9 bytes (chosen for testing to be a small number), i.e. socket_.async_read_some(boost::asio::buffer(buf, 9), callback). Then I feed small amounts of data to the server and the read command only seems to callback when it has a full 9 bytes to read, not immediately after writing, say, 4 bytes, as I expected. What determines when the callback occurs and why doesn't it occur as soon as some data is available on the socket?
The socket.async_read_some() operation has the same completion conditions as its synchronous counterpart, the socket.read_some() operation. The operation is considered complete when either:
Upon completion of the operation (success or failure), the ReadHandler will be posted into the io_service for deferred invocation. At this point, the ReadHandler may be invoked by any thread servicing the io_service.
When small amounts of data are being written to a socket, such as in the problem description, one typically observes the behavior of data not being sent until subsequent data is written to the socket because of Nagle's algorithm. In short, many systems will attempt to mitigate IP/TCP congestion by concatenating small outbound messages into a single message that is then sent. To explicitly disable this behavior on a per-socket basis, set the boost::asio::ip::tcp::no_delay option:
boost::asio::ip::tcp::socket socket(io_service);
// ...
boost::asio::ip::tcp::no_delay option(true);
socket.set_option(option);
When in doubt, monitor the wire traffic with a packet analyzer, such as Wireshark or tcpdump, on both the sender and receiver. One can often use these tools to at quickly identify whether the problem is on the sending or receiving side. Upon identifying the offending side, one often has to dive into kernel, driver, or hardware documentation to identify configurations that may be the source of the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With