vendredi 24 juin 2016

Buffer sometimes wrong while received from TCP with boost socket

The problem: The problem: I have a problem with async_read_some in boost::asio. Sometimes the variable m_deBuff changes inside the callback method TCPSession::handle_read. I can’t figure out why this happens? I’m using a tcp socket on the other side and I have analyzed the data over wireshark and it looks intact. I’m also sending and receiving on the loopback interface 127.0.0.1. It happens more often when I put std::cout < str; and sleep inside handle_read. The code: void TCPSession::start( TCPSessionListner* parent ) { std::cout << "TCPSession::started" << std::endl; m_parent = parent; m_socket.async_read_some(boost::asio::buffer(m_deBuff, MAX_LEN), boost::bind(&TCPSession::handle_read, weak_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void TCPSession::handle_read(const boost::system::error_code& error, size_t bytes_transferred) { if (!error) { m_workingBuffer.insert(m_workingBuffer.end(), m_deBuff, m_deBuff + bytes_transferred); if( m_parent != 0 ) { if (false == m_rawRead) { std::vector< std::string > messages; Messages::TcpStreamToMessages(m_workingBuffer, messages); m_parent->onData( messages, m_sessionID ); } if (false == m_workingBuffer.empty() && true == m_rawRead) { std::string str(m_workingBuffer.begin(), m_workingBuffer.end()); std::cout << str; boost::this_thread::sleep(boost::posix_time::milliseconds(1000)); // HERE, while debugging after std::cout m_deBuff has changed (only sometimes)... //m_parent->onRawData(m_workingBuffer, m_sessionID); m_workingBuffer.clear(); } } m_socket.async_read_some(boost::asio::buffer(m_deBuff, MAX_LEN), boost::bind(&TCPSession::handle_read, weak_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else { if( m_parent != 0 ) { m_parent->onSessionDisconnected( m_sessionID ); } } }

Aucun commentaire:

Enregistrer un commentaire