正确关闭 TCP 套接字 [英] Properly close a TCP socket

查看:68
本文介绍了正确关闭 TCP 套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

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?

推荐答案

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

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

2) 继续从套接字中read,直到出现错误或连接关闭.

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

3) 现在关闭套接字.

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

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.

这篇关于正确关闭 TCP 套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆