2011-05-31 77 views
-2
bool Connection::Receive(){ 
    std::vector<uint8_t> buf(1000); 
    boost::asio::async_read(socket_,boost::asio::buffer(buf,1000), 
      boost::bind(&Connection::handler, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); 

    int rcvlen=buf.size(); 
    ByteBuffer b((std::shared_ptr<uint8_t>)buf.data(),rcvlen); 
    if(rcvlen <= 0){ 
     buf.clear(); 
     return false; 
    } 
    OnReceived(b); 
    buf.clear(); 
    return true; 
} 

該方法工作正常,但只有當我在它內部製造一個斷點時。等待接收的時機是否存在問題?沒有斷點,就沒有收到任何東西。我是否在加速asio async_read中獲得競爭條件?

+0

我不明白你的問題。嘗試使用','或'。'例如... – nabulke 2011-05-31 05:59:30

+0

@nabulke現在檢查它 – Abanoub 2011-05-31 06:05:31

+5

請不要使用俚語。 「如此奇怪」不是一個問題,「w8ting」不是一個真正的單詞。這不是一個論壇。 – Soviut 2011-05-31 06:22:24

回答

4

您正嘗試在啓動異步操作後立即從接收緩衝區中讀取數據,而無需等待完成,這就是爲什麼當您設置斷點時它會工作。

您的async_read之後的代碼屬於Connection::handler,因爲這是您告知async_read在接收到某些數據後調用的回調。

你通常想要的是一個start_readhandle_read_some功能:

void connection::start_read() 
{ 
    socket_->async_read_some(boost::asio::buffer(read_buffer_), 
     boost::bind(&connection::handle_read_some, shared_from_this(), 
      boost::asio::placeholders::error, 
      boost::asio::placeholders::bytes_transferred)); 
} 

void connection::handle_read_some(const boost::system::error_code& error, size_t bytes_transferred) 
{ 
    if (!error) 
    { 
     // Use the data here! 

     start_read(); 
    } 
} 

注意shared_from_this,如果你希望你的連接的生命週期由優秀我的號碼被自動的照顧是很重要的/ O請求。請務必從boost::enable_shared_from_this<connection>派生出你的課程,並且只能用make_shared<connection>來創建它。

要實施這個,你的構造應該是私有的,你可以添加好友聲明(的C++ 0x版本;如果你的編譯器不支持此功能,你必須填上自己的論點正確的號碼):

template<typename T, typename... Arg> friend boost::shared_ptr<T> boost::make_shared(const Arg&...); 

還要確保您的接收緩衝區在回調被調用時仍然存在,最好是通過使用連接類的靜態大小緩衝區成員變量。

+0

@xDD它給了我這個錯誤'tr1 :: bad_weak_ptr' – Abanoub 2011-05-31 07:02:44

+0

確保你沒有在構造函數中使用'shared_from_this()',因爲那時不是所有東西都被設置好了。您可能想要創建一個公共靜態幫助函數,該函數使用'make_shared'創建一個連接,然後調用'start_read()'。 – xDD 2011-05-31 07:05:46

+0

@xDD看我有三類檢查他們你也會明白我試圖做 連接 http://pastebin.com/zWQHVgSp 連接工廠 http://pastebin.com/fyx4eZdZ 服務器 HTTP: //pastebin.com/3DAcH7Db 我不知道如何讓它工作,你告訴我:/ – Abanoub 2011-05-31 07:22:12