提升asio basic_socket问题

boost asio basic_socket issue

本文关键字:socket 问题 basic asio 提升      更新时间:2023-10-16

我是一名游戏开发人员。我在开发聊天功能时遇到了这个问题。我的游戏在Iphone上运行时崩溃了,这是由asio lib中的basic_socket::close引起的。这是源代码:

  /// Close the socket.
  /**
   * This function is used to close the socket. Any asynchronous send, receive
   * or connect operations will be cancelled immediately, and will complete
   * with the boost::asio::error::operation_aborted error.
   *
   * @throws boost::system::system_error Thrown on failure. Note that, even if
   * the function indicates an error, the underlying descriptor is closed.
   *
   * @note For portable behaviour with respect to graceful closure of a
   * connected socket, call shutdown() before closing the socket.
   */
  void close()
  {
    boost::system::error_code ec;
    this->get_service().close(this->get_implementation(), ec);
    boost::asio::detail::throw_error(ec, "close");
  }

所以我的问题是,为什么它总是抛出一个异常?(顺便说一句,如果你在boost上不使用异常功能,throw_error方法最终会调用std::terminate(),这会使程序崩溃。)

---------------------------更新-------------------------

我的游戏可能会关闭http请求并重新启动它。当它关闭请求时,它会转到这里关闭套接字。我只是不知道为什么它会在接近时抛出异常,我认为这是没有必要的,不是吗?

我已经用try&接住在boost中的无使用异常情况下,我调用std::set_terminate()来避免崩溃。所以我不要求解决方案,而是询问原因:)

basic_socket::close()是操作系统特定的::close()::closesocket()调用的精简包装器。::close()的iOS文档指出,如果出现以下情况,它将失败:

  • [EBADF]-不是有效的活动文件描述符
  • [EINTR]-执行被一个信号中断
  • [EIO]—以前未提交的写入遇到输入/输出错误

检查异常或error_code以确定故障类型。


正如Boost.Asio basic_socket::close()文档中所建议的那样,应该考虑在关闭套接字之前调用shutdown(),以获得优雅关闭时的可移植行为。此外,考虑对函数使用非抛出重载,例如这个basic_socket::close(ec)重载:

boost::asio::ip::tcp::socket socket(io_service);
boost::system::error_code error;
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error);
if (error)
{
  // An error occurred.
}
socket.close(error);
if (error)
{
  // An error occurred.
}