我试图从套接字中读取特定的字节数。我的服务器正在发送:
1)byte [0] - 消息的长度 2)byte [1:N] - 实际消息
如何读取第一个字节,然后使用boost :: asio :: ip :: tcp :: socket :: read读取剩余的字节?以下是代码段:
// 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(...)
{
}
}
答案 0 :(得分:2)
您需要为单字节头准备一个缓冲区,然后为该消息准备另一个缓冲区。一个简化的例子可能是
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;