Boost::asio 套接字 - 如何干净地断开它们?

发布于 2024-10-06 19:07:10 字数 174 浏览 0 评论 0原文

我正在为我的服务器应用程序使用 boost 异步套接字。我创建了一个disconnect()函数,它调用boost的close(),然后删除套接字(操作符delete)。 当从异步之一调用该函数时就可以了。处理程序,但是当我从主代码库内部调用它时,整个应用程序在其中一个异步处理程序处崩溃。 如何在boost中很好地关闭套接字?

I am using boost asynchronous sockets for my server application. I've created a disconnect() function that calls boost's close() and then deletes the socket (operator delete).
And it's alright when the function is called from one of the async. handlers, but when I call it from inside my main codebase, the whole application crashes at one of the async handlers.
How to close a socket nicely in boost?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

朮生 2024-10-13 19:07:10

确保只要可能使用该对象的处理程序存在,该对象就处于活动状态。

在您调用 close 之后,可能会调用使用此套接字的处理程序之一(因为它
向处理程序报告错误),然后访问死指针...

通常,可以使用 boost::shared_ptrboost::enable_shared_from_this 轻松完成生命周期处理并传递它在处理程序中。请参阅 Boost.Asio 提供的大量示例。

一旦您熟悉了这种技术,您提出的问题对您来说就会显得微不足道。

Make sure that the object is alive as long as handlers that may use it exist.

It is likely what one of handlers that uses this socket is called after you call close (as it
reports the error to handler) and then accesses to dead pointer...

Usually, life time handling can be easily done with boost::shared_ptr and boost::enable_shared_from_this and passing it in handlers. See numerous examples provided with Boost.Asio.

Once you get familiar with this technique the question you asked would look trivial for you.

謸气贵蔟 2024-10-13 19:07:10

您确实还想研究套接字上的关闭方法。它不会解决您崩溃的应用程序。上面的 Artyom 已经解释了其中的原因,但仍然很有趣。
如果您关闭套接字而不调用 shutdown,可能会导致发送 RST,而不是正常的 FIN 握手。

You do want to look into the shutdown method on a socket as well. It will not solve your crashing application. Artyom above already explained the cause of that, but it is interesting nonetheless.
If you close a socket without calling shutdown it might result in a RST being send instead of a gracefull FIN handshake.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文