问题
I am trying to read specific number of bytes from the socket. My server is sending:
1) byte[0] - length of the message 2) byte[1:N] - the actual message
How do I read the first byte and then read the remaining bytes using boost::asio::ip::tcp::socket::read ? Here is the code snippet:
// receive data through the socket
void TCPTestClient::ReceiveData( )
{
try
{
boost::system::error_code error;
boost::asio::streambuf receivedStreamBuffer;
// reserve 512 bytes in output sequence
boost::asio::streambuf::mutable_buffers_type bufs =receivedStreamBuffer.prepare( 512 );
boost::asio::read( m_socket,
bufs,
error );
// transfer the buffer contents to string
std::istream is( &receivedStreamBuffer );
is >> m_receivedMessageStr;
// throw exception if error occurred
if ( error )
{
throw NetworkTestFailedException( error.message() );
}
}
catch(...)
{
}
}
回答1:
You'll want to prepare a buffer for the one byte header, then prepare another buffer for the message. A simplified example might be
boost::asio::read(
m_socket,
receivedStreamBuffer.prepare(1),
error
);
if ( error ) {
std::cerr << "Read header failed: " << boost::system::system_error(error).what() << std::endl;
return;
}
receivedStreamBuffer.commit(1);
std::istream header( &receivedStreamBuffer );
uint8_t size;
header >> size;
// reserve message size in output sequence
boost::asio::read(
m_socket,
receivedStreamBuffer.prepare( size ),
bufs,
error
);
if ( error ) {
std::cerr << "Read message failed: " << boost::system::system_error(error).what() << std::endl;
return;
}
receivedStreamBuffer.commit( size );
// transfer the buffer contents to string
std::istream is( &receivedStreamBuffer );
is >> m_receivedMessageStr;
来源:https://stackoverflow.com/questions/14324060/boost-receive-data-from-the-tcp-socket