正确关闭 TCP 套接字
“优雅地”关闭 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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.