我是游戏开发者。我在开发聊天功能时遇到了这个问题。我的游戏在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& amp解决了由异常引起的问题抓住。在boost中的非使用异常情况下,我调用std :: set_terminate()来避免崩溃。所以我没有要求解决方案,我问为什么:)
答案 0 :(得分:1)
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.
}