C ++ boost :: asio :: async_write send problems

When I call async_write() , the remote peer does not receive data until I call async_write() again. For example, I have 3 packages, a , b and c :

 SendPacket(a); // the remote side receives nothing SendPacket(b); // the remote side receives packet a SendPacket(c); // the remote side receives packet b 

This is my code to send:

 void Session::SendPacket(packet p) { dword len = p.Lenght(); byte* buffer_send = new byte[len + 4]; //4 cause of the header memcpy(buffer_send + 4, p.GetRaw(), len); // copy everything to the buffer +4, 0-4 is header m_codec.EncodePacket(buffer_send, len); boost::asio::async_write(m_socket, boost::asio::buffer(buffer_send, len + 4), boost::bind(&Session::OnPacketSend, this, len + 4, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, buffer_send)); } void Session::OnPacketSend(int len, const boost::system::error_code &e, size_t bytes_transferred, byte* buf) { // this asynchronously fires when packet data is sent delete[] buf; if (e || bytes_transferred != len) { Stop(); return; } } 

And I use it as follows:

 packet pp; pp.WriteWord(0); pp.WriteDword(4); pp.WriteWord(0); SendPacket(pp); 

In addition, when SendPacket() receives packet by value instead of reference, a failure occurs.

Gr

+1
source share
1 answer

When small amounts of data are written to the socket, for example, in the source code (12 bytes ~), the behavior of data that is not sent until subsequent data is written to the socket due to the Nagle algorithm is usually observed. In short, many systems will try to mitigate IP / TCP congestion by combining small outgoing messages into a single message, which is then sent. To explicitly disable this behavior based on each socket, set boost::asio::ip::tcp::no_delay :

 boost::asio::ip::tcp::socket socket(io_service); // ... boost::asio::ip::tcp::no_delay option(true); socket.set_option(option); 

With sufficient bandwidth, disabling Nagle can lead to increased bandwidth. However, it is still worth considering the application protocol and logic much more to determine when or what data can be buffered, and when it needs to be sent immediately.

+2
source

Source: https://habr.com/ru/post/1213256/


All Articles