When I lose connection, in my server code, I try to reconnect in a loop forever. Once I reconnect, I send a login message to the component I am connected to. That component then sends back a login response that looks like "MyResponse"
The initial connection works fine. After I reconnect, however, I get garbage before the expected message, that looks like: "ýMyResponse"
After googling this. I see many questions on Stack Overflow about the boost::asio::streambuf that is used for async sockets in boost::asio. Particularly about reusing he buffer. I have followed the advice there and called consume upon disconnecting. In other words, I call boost::asio::streambuf::consume after I call shutdown and close on my socket, after being called back with an error on recv in response to a call to recv_until.
I have also used wireshark to make sure that the garbage character is not being sent and it is not.
After much debugging, it appears as though the calls to consume are injecting a character rather than clearing out all characters.
Here is a minimal example:
#include <boost/asio.hpp>
#include <iostream>
#include <sstream>
#include <string>
int main()
{
boost::asio::streambuf buffer;
std::cout << "buffer size " << buffer.size() << std::endl;
buffer.consume(std::numeric_limits<size_t>::max());
std::cout << "buffer size " << buffer.size() << std::endl;
std::istream is(&buffer);
std::string contents;
is >> contents;
std::cout << "Contents: " << contents << std::endl;
std::cout << "buffer size " << buffer.size() << std::endl;
return 0;
}
Output:
buffer size 0
buffer size 1
Contents: ²
buffer size 0
Expected Output:
buffer size 0
buffer size 0
Contents:
buffer size 0
If I do not use consume, I get some of the message, previous to disconnect, before the first message after reconnection, in my server code.
If I do use consume, I get a garbage character.
See:
Working with boost::asio::streambuf
std::size_t
toint
results in-1
), that is then passed togbump()
with no bound checks that may result in undefined behavior. I can investigate in more detail later, but in the meantime, to consume the entire streambuf, consider explicitly passingstreambuf::size()
tostreambuf::consume()
. – Melisa