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对象后,它被io_service.run()调用?或者我可能必须在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));
}
相关文章:
- boost::asio UDP 广播客户端仅接收"fast"数据包
- 如何使用发送数据包所花费的时间计算两个节点之间的距离?
- 发送固定大小的 UDP 数据包
- pcap_handler回调仅在使用 NPCAP v0.9991 时包含空数据包
- 在 c++ 中解析数据包数据的最佳方法是什么?
- 接受函数在发送数据包时等待
- 如何在 omnet++ 中发送自定义数据包?
- 数据包访问实践
- 在C++中创建一个简单的数据包路由器,如何跟踪"客户端"?
- 德拉吉诺 LG01-S 收到异常数据包并停止工作
- 将数据包从C++服务器发送到NodeJs服务器时出现MessagePack解码错误
- 使用C++将UDP数据包存储在Structure中
- FFmpeg av_read_frame从音频流返回数据包
- 为什么操作系统正在更改我的数据包的指定传出端口
- 是否可以将多个结构作为一个数据包存储在一个函数中,然后传递给其他函数并在那里提取?
- recvfrom 只收到几个数据包,之后它进入等待状态
- 如何调试由 C++ 编写的 npm 数据包
- 如何在INET的应用层中发送广播数据包
- 定时发送和接收相同的数据包
- Boost::asio如何实现定时数据包发送功能