How to detect when a boost tcp socket disconnects(如何检测 boost tcp 套接字何时断开连接)
问题描述
假设我有一个套接字:
std::shared_ptr<tcp::socket> socket( new tcp::socket(acceptor.get_io_service()) );
acceptor.async_accept( *socket, std::bind( handleAccept, this, std::placeholders::_1, socket, std::ref(acceptor)) );
我将一个weak_ptr存储到容器中的所述套接字中.我需要这个是因为我想允许客户端请求其他客户端的列表,以便他们可以相互发送消息.
And I store a weak_ptr to the said socket in a container. I need this because I want to allow clients to request for a list of other clients, so they can send messages to each other.
clients_.insert(socket); // pseudocode
然后我运行一些异步操作
Then I run some async operations
socket->async_receive( boost::asio::buffer(&(*header), sizeof(Header))
, 0
, std::bind(handleReceiveHeader, this, std::placeholders::_1, std::placeholders::_2, header, socket));
如何检测连接何时关闭,以便从容器中删除套接字?
How do I detect when the connection is closed so I can remove my socket from the container?
clients_.erase(socket); // pseudocode
推荐答案
TCP 套接字断开通常在 asio
中由 eof
或 connection_reset<发出信号/代码>.例如
A TCP socket disconnect is usually signalled in asio
by an eof
or a connection_reset
. E.g.
void async_receive(boost::system::error_code const& error,
size_t bytes_transferred)
{
if ((boost::asio::error::eof == error) ||
(boost::asio::error::connection_reset == error))
{
// handle the disconnect.
}
else
{
// read the data
}
}
我使用 boost::signals2
来表示断开连接,尽管您始终可以将指向函数的指针传递给您的套接字类,然后调用它.
I use boost::signals2
to signal the disconnect although you can always pass a pointer to a function to your socket class and then call that.
请注意您的套接字和回调生命周期,请参阅:boost-异步函数和共享指针
Be careful about your socket and callback lifetimes, see: boost-async-functions-and-shared-ptrs
这篇关于如何检测 boost tcp 套接字何时断开连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检测 boost tcp 套接字何时断开连接


- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01