简体   繁体   English

Boost.Asio socket析构函数关闭连接?

[英]Boost.Asio socket destructor closes connection?

What exactly does the destructor of boost::asio::ip::tcp::socket do? boost::asio::ip::tcp::socket的析构函数到底是做什么的? I can't tell, even after scouring Boost docs and source code, if I need to use 我不知道,即使在浏览Boost文档和源代码之后,如果我需要使用它

socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both);
socket->close();

before calling 在打电话之前

delete socket;

Do I need to close the socket manually, or does the destructor handle this? 我是否需要手动关闭套接字,或者析构函数是否处理此问题?

When a socket is destroyed, it will be closed as-if by socket.close(ec) during the destruction of the socket. 当一个插座被破坏,它将作为-如果由封闭socket.close(ec)的插座的破坏期间。

I/O objects, such as socket , derive from basic_io_object . I / O对象(如socket )派生自basic_io_object Within the basic_io_object destructor , destroy() will be invoked on the I/O object's I/O service, passing in an instance of the implementation_type on which the I/O object's service will operate. basic_io_object析构函数中 ,将在I / O对象的I / O服务上调用destroy() ,传入I / O对象服务将在其上运行的implementation_type实例。 In the case of socket, destroy() will be invoked on a type that fulfills the SocketService type requirement, closing the underlying socket. 在socket的情况下,将在满足SocketService类型要求的类型上调用destroy() ,关闭底层套接字。 In the documentation below, a is an instance of a socket service class, and b is an instance of the implementation_type for the socket service class: 在下面的文档中, a是套接字服务类的实例, b是套接字服务类的implementation_type的实例:

a.destroy(b) : a.destroy(b)

[...] Implicitly cancels asynchronous operations, as if by calling a.close(b, ec) . [...]隐式取消异步操作,就像调用a.close(b, ec)

a.close(b, ec) : a.close(b, ec)

If a.is_open() is true, causes any outstanding asynchronous operations to complete as soon as possible. 如果a.is_open()为true,则会导致任何未完成的异步操作尽快完成。 Handlers for cancelled operations shall be passed the error code error::operation_aborted . 取消操作的处理程序应传递错误代码error::operation_aborted

post: !a.is_open(b) . 发布: !a.is_open(b)

No you don't need to close it. 不,你不需要关闭它。 Though it might be cleaner to do so, if you want to report any errors surrounding protocol shutdown. 虽然这样做可能更干净,但如果要报告协议关闭周围的任何错误。

The destructor just /appears/ to be empty, that's a good sign of Modern C++: 析构函数只是/出现/是空的,这是Modern C ++的一个好兆头:

The answers have skipped over the issue of shutdown(). 答案已经跳过了shutdown()的问题。 From the close() documentation, "For portable behaviour with respect to graceful closure of a connected socket, call shutdown() before closing the socket". 从close()文档,“关于正常关闭连接套接字的可移植行为,在关闭套接字之前调用shutdown()”。

If deleting the socket does an implicit close, it seems that a call to shutdown() is still recommended before deleting it. 如果删除套接字是隐式关闭,则在删除之前似乎仍然建议调用shutdown()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM