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

2021-12-24 00:00:00 sockets tcp c++ boost boost-asio

假设我有一个套接字:

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

相关文章