簡體   English   中英

boost :: asio如何實現定時數據包發送功能?

[英]boost::asio how to implement a timed packet send feature?

我有一個服務器應用程序,該應用程序使用boost :: asio的異步讀/寫功能與連接的客戶端進行通信(直到客戶端斷開連接)。

到目前為止,一切都很好,但我想實現某種定時方法,即服務器在經過一定時間后自行發送數據包。

我主要遵循boost :: asio網站上的教程/示例,因此我的程序基本上具有與給定示例相同的結構。

我試圖通過創建一個asio :: deadline計時器對象並將其傳遞給我已經通過調用io_service.run()來“調用”的io_service對象來實現此功能:

asio::deadline_timer t(*io, posix_time::seconds(200));
t.async_wait(boost::bind(&connection::handle_timed, 
                this, boost::asio::placeholders::error));

而且handle_timed處理程序如下所示:

void connection::handle_timed(const system::error_code& error)
{
    //Ping packet is created here and gets stored in send_data

    async_write(socket_, asio::buffer(send_data, send_length), 
                boost::bind(&connection::handle_write, this, boost::asio::placeholders::error));
}

但是我遇到的問題是,deadline_timer沒有等待給定的時間,他幾乎立即進入了處理程序函數並想要發送數據包。

就像他一開始就處理異步操作一樣,那當然不是我想要的。

難道是我無法在使用io_service.run()調用io_service對象后向其添加新的“對象”嗎? 或者,也許之后我必須專門將其包括在io_service對象的工作隊列中?

另外,我在理解如何實現此目標而又不與常規消息流量混淆時遇到麻煩。

您可以隨時將工作添加到io_service 您應該檢查你的錯誤async_wait()的回調,它看起來對我來說,你的deadline_timer超出范圍

asio::deadline_timer t(*io, posix_time::seconds(200));
t.async_wait(boost::bind(&connection::handle_timed, 
                this, boost::asio::placeholders::error));
...
// t goes out of scope here

您應該使其成為connection類的成員,就像socket_一樣。 或者,使用boost::enable_shared_from_this並將副本保存在完成處理程序中:

const boost::shared_ptr<asio::deadline_timer> t(new asio::deadline_timer(*io, posix_time::seconds(200)));
t.async_wait(boost::bind(&connection::handle_timed, 
                this, boost::asio::placeholders, t));

和您的完成處理程序

void connection::handle_timed(
    const system::error_code& error,
    const boost::shared_ptr<asio::deadline_timer>& timer
    )
{
    //Ping packet is created here and gets stored in send_data

    async_write(socket_, asio::buffer(send_data, send_length), 
                boost::bind(&connection::handle_write, this, boost::asio::placeholders::error));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM