正确关闭 TCP 套接字

发布于 2024-12-27 01:51:00 字数 268 浏览 0 评论 0原文

“优雅地”关闭 TCP 套接字的推荐方法是什么?

我了解到,在读取()主机缓冲区中的所有剩余数据之前关闭()可能会给远程主机带来问题(他可能会丢失接收缓冲区中已被确认但尚未读取的所有数据)通过他的申请)。这是正确的吗?

避免这种情况的好方法是什么?有没有什么方法可以告诉 API 我并不真正关心由于我忽略任何剩余的缓冲数据并关闭套接字而导致的数据丢失?

或者我是否必须在应用程序协议级别考虑问题并使用某种隐式或显式的“传输结束”信号来让对方知道关闭用于读取的套接字是安全的?

What is the recommended way to "gracefully" close a TCP socket?

I've learned that close()ing before read()ing all the remaining data in my host buffer can cause problems for the remote host (he could lose all the data in his receive buffer that has been acked, but not yet been read by his application). Is that correct?

What would be a good approach to avoid that situation? Is there some way to tell the API that I don't really care about data being lost due to my ignoring any remaining buffered data and closing the socket?

Or do I have to consider the problem at the application protocol level and use some kind of implicit or explicit "end of transmission" signal to let the other party know that it's safe to close a socket for reading?

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

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

发布评论

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

评论(1

诗酒趁年少 2025-01-03 01:51:00

1) 调用shutdown表示不再向套接字写入任何数据。

2) 继续从套接字读取,直到出现错误或连接关闭。

3) 现在关闭套接字。

如果您不这样做,您可能会在仍有数据需要读取时关闭连接。这将导致不优雅的关闭。

1) Call shutdown to indicate that you will not write any more data to the socket.

2) Continue to read from the socket until you get either an error or the connection is closed.

3) Now close the socket.

If you don't do this, you may wind up closing the connection while there's still data to be read. This will result in an ungraceful close.

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