Good evening everyone!

While writing a chat server using either Boost, there was a problem reading the data from the stream .

The async_read function reads character-by-character data in m_read_buffer from the stream and is called by the read_complete function. During a random call to do_read to read data into the buffer from async_read, characters begin to overwrite the buffer.

enum { max_msg = 1024 }; char read_buffer_[max_msg]; void do_read() { async_read(m_sock, buffer(read_buffer_), boost::bind(read_complete,_1,_2), boost::bind(on_read,_1,_2)); } size_t read_complete(const boost::system::error_code & err, size_t bytes) { if ( err) return 0; bool found = std::find(read_buffer_, read_buffer_ + bytes, '\n') < read_buffer_ + bytes; // we read one-by-one until we get to enter, no buffering return found ? 0 : 1; } 

Consider an example of data sent from a client, and we will observe how our buffer changes all the time. Data from the client: "I'm user want to log in \ n" . In the example, it is clear that at first the character with an odd index is added to the end of the buffer, and following it, it rewrites the previous character. Thus, the characters that are placed in even places in the data line are placed in the buffer.

The m_read_buffer buffer is separated by commas during various iterations:

"" , I , ' , ' m , '**, **' u , 's , ' se , 'sr , ' sr **, ** 'sra , ' srn , 'srnd , ' srn **, * * 'srn w , ' srn a , 'srn an , ' srn at , 'srn at **, **' srn att , 'srn ato , ' srn ato **, ** 'srn atol , ' srn atolo , ' srn atolg , 'srn atolg **, **' srn atolgi , 'srn atolgin , ' srn atolgi \ n .

    1 answer 1

    Get the constant out of enum . Your buffer limit is 8 characters, not 1024 .

    • Did - did not help (( - toschev.andrey