2013-02-14 73 views
4

現在我通過以下方式接收文本:使用boost asio接收文本的最有效方法?

boost::asio::streambuf buffer;   
    std::string text; 
    while(true) { 
     try 
     { 

      boost::asio::read_until(*m_pSocket, buffer, "END"); 

      text = boost::asio::buffer_cast<const char*>(buffer.data()); 
      buffer.consume(text.size()); 

      boost::asio::write(*m_pSocket, boost::asio::buffer(text, text.size())); 
      std::cout << text<< std::endl; 
     } 
     catch (std::exception& e) 
     { 
      std::cerr << "Exception: " << e.what() << "\n"; 
      break; 
     }  
    } 

收到序列「END」當我剛收到的回波文本到客戶端。我的問題:

在我看來非常inefficent到流緩衝轉換爲字符串,然後消耗從它的文字標誌。以良好,乾淨和高效的方式處理收到的數據的正確方式是什麼?

+0

如果你需要的是發送'streambuf',您可以直接做到這一點,沒有用'string'。 – 2013-02-14 15:15:23

+0

不是。在目前的情況下,這已經足夠了,但是我的應用程序在以後會變得更復雜 – Anonymous 2013-02-14 15:24:03

+0

'buffer_cast ''會返回'const char *'。從這一點你可以用這個常量緩衝區來做任何你想要的。 – 2013-02-14 15:29:31

回答

2

總之,你將有接收到的文本的兩個副本:一個在流緩衝,其他的的字符串中。 boost::asio::buffer只是一個指針,指向字符串和大小。

如果直接從發送的StringBuf該通告是不是一種選擇,那就是你可以得到最好的。但是,我不明白首先發回streambuf的內容並將其用於內部使用後應該是什麼問題。

您的代碼看起來是這樣的,那麼:

boost::asio::streambuf buffer;   
while(true) { 
    try 
    { 
     auto size = boost::asio::read_until(*m_pSocket, buffer, "END"); 

     //send back the seuqence: 
     auto begin = boost::asio::buffer_cast<const char*>(buffer.data()); 
     boost::asio::write(*m_pSocket, boost::asio::buffer(begin, size)); 

     //consume the content... 
     std::istream is(&buffer); 
     is >> /* whatever fits here... */ 
    } 
    catch (std::exception& e) 
    { 
     std::cerr << "Exception: " << e.what() << "\n"; 
     break; 
    }  
} 

除此之外,我不會發回整個序列。根據發送的序列的平均大小,可以更好地計算動態校驗和並將其發回,而不是整個序列。

相關問題