Boost logo

Boost Users :

Subject: [Boost-users] asio async_read_some handler called but has bad data
From: Matt Fair (matt.fair_at_[hidden])
Date: 2012-05-08 13:19:35


Hello,

I have client/server code similar to the chat server, but I am using async_read_some/async_write_some. I am having a problem with my client when the server sends a bunch of data to it at one time. What happens is that it works for a while then readComplete is called with a full buffer and no error set, but my buffer has garbage and eventually causes my socket to crash. I wanted to check with everyone to see if they have seen this problem before, and if there is anything glaring that I'm doing wrong here with boost::asio. I noticed that in the http server it is using shared_from_this, is this necessary?
If the server is sending the client data with async_write faster than I can processes it with async_read, could it cause some buffer overrun?

Thanks,
Matt

My buffer is defined as a private array:
 static const unsigned int m_maxReadLength = 1024; // maximum amount of data to read in one operation
 char m_readBuffer[m_maxReadLength];

The client starts to read the socket with:
void TCPSocket::readStart()
{
 if(isOpen())
 {
   // Start an asynchronous read and call read_complete when it completes or fails
   m_pSocket->async_read_some(
       boost::asio::buffer(m_readBuffer, m_maxReadLength), boost::bind(
           &TCPSocket::readComplete, this, boost::asio::placeholders::error,
           boost::asio::placeholders::bytes_transferred));
 }
}

My readComplete method is:
void TCPSocket::readComplete(const boost::system::error_code& error, size_t bytes_transferred)
{
 // the asynchronous read operation has now completed or failed and returned an error
 if(!error && bytes_transferred <= m_maxReadLength)
 {
     //convert to string
     const string buffer(&m_readBuffer[0], &m_readBuffer[bytes_transferred]);
     //buffer eventually becomes junk
     .....
 }
 else
 {
    //handle error
 }
 readStart(); //read some more data
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net