2010-05-07 57 views
0

美好的一天。如何使用boost :: asio發送大對象

我通過網絡使用boost :: asio接收大對象。

而且我有一個代碼:

for (int i = 1; i <= num_packets; i++) 
boost::asio::async_read(socket_, boost::asio::buffer(Obj + packet_size * (i - 1), packet_size), boost::bind(...)); 

哪裏My_Class * Obj。 我懷疑這種方法是否可行(因爲我有一個指向這裏的對象的指針)?或者如何使用字節固定大小的數據包接收此對象會更好?

在此先感謝。

回答

0

我覺得Boost.Asio的文檔中的http_client例子說明它比我能更好: http://www.boost.org/doc/libs/1_43_0/doc/html/boost_asio/example/http/client/async_client.cpp

你不需要操心包,你會得到一個TCP流,並從屬於插槽閱讀到溪流。故事結局。你需要類似這樣的東西,不同之處在於你不會讀取到std :: cout的響應,而是從它重建對象(不確定這是否適用於對象或簡單類型)。

class client 
{ 
... 
    void handle_read_content(const boost::system::error_code& err) 
    { 
     if (!err) 
     { 
      // Write all of the data that has been read so far. 
      std::cout << &response_; 

      // Continue reading remaining data until EOF. 
      boost::asio::async_read(socket_, response_, 
      boost::asio::transfer_at_least(1), 
      boost::bind(&client::handle_read_content, this, 
      boost::asio::placeholders::error)); 
     } 
     else if (err != boost::asio::error::eof) 
     { 
      std::cout << "Error: " << err << "\n"; 
     } 
    } 
... 
    boost::asio::ip::tcp::socket socket_; 
    boost::asio::streambuf response_; 
}; 

您還應該考慮序列化,例如Boost.Serialization。 如果您想傳輸複雜的對象,永遠不會傷害。