如何检测,当升压TCP套接字断开连接 [英] How to detect when a boost tcp socket disconnects
问题描述
假设我有一个socket:
的std :: shared_ptr的< TCP ::插座>插座(新TCP ::插座(acceptor.get_io_service()));
acceptor.async_accept(*插座的std ::绑定(handleAccept,对此,性病::占位符:: _ 1,插座的std :: REF(受体)));
和我存储的weak_ptr到在容器中的所述插座。我需要这个,因为我想允许客户端请求的其他客户的名单,这样他们就可以将消息发送给对方。
clients_.insert(插座); //伪code
然后我运行一些异步操作
插座> async_receive(升压:: ASIO ::缓冲区(及(*头)的sizeof(头))
,0
,性病::绑定(handleReceiveHeader,对此,性病::占位符:: _ 1,性病::占位符:: _ 2,头,插座));
我如何检测当连接被关闭,所以我可以从容器中删除我的插座?
clients_.erase(插座); //伪code
一个TCP套接字脱节通常是在 ASIO
由信号EOF
或 connection_reset
。例如。
无效async_receive(升压::系统::错误_ code常量和放大器;错误,
为size_t bytes_transferred)
{
如果((提高:: ASIO ::错误:: EOF ==错误)||
(::提高:: ASIO ::错误== connection_reset错误))
{
//处理脱节。
}
其他
{
//读取数据
}
}
我用的boost :: signals2
信号断开虽然可以指向一个函数总是传递给您的插座类,然后调用。
要小心你的插座和回调生命周期,请参见:<一href=\"http://stackoverflow.com/questions/11356742/boost-async-functions-and-shared-ptrs/19622084#19622084\">boost-async-functions-and-shared-ptrs
Suppose I have a socket:
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)) );
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
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
}
}
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.
Be careful about your socket and callback lifetimes, see: boost-async-functions-and-shared-ptrs
这篇关于如何检测,当升压TCP套接字断开连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!