如何检测 boost tcp 套接字何时断开连接

How to detect when a boost tcp socket disconnects(如何检测 boost tcp 套接字何时断开连接)

本文介绍了如何检测 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 中由 eofconnection_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 套接字何时断开连接

基础教程推荐