2013-01-14 423 views
1

我想從套接字讀取特定數量的字節。我的服務器發送:Boost從TCP套接字接收數據

1)字節[0] - 長度消息 2)字節的[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(...) 
     { 

     } 
    } 

回答

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;