+-
c – 为什么我应该在关闭套接字之前使用shutdown()?
参见英文答案 > close vs shutdown socket?                                    8个
在这个MSDN页面上:

Sending and Receiving Data on the Client

它建议使用以下方法关闭套接字的发送方:

shutdown(SOCK_ID, SD_SEND);

我为什么要?

也许我没有,它只是一个推荐?也许是为了节省记忆?也许速度?

有没有人有想法?

最佳答案
答案在 shutdown()文档中:

If the how parameter is SD_SEND, subsequent calls to the send function are disallowed. For TCP sockets, a FIN will be sent after all data is sent and acknowledged by the receiver.

To assure that all data is sent and received on a connected socket before it is closed, an application should use shutdown to close connection before calling closesocket. One method to wait for notification that the remote end has sent all its data and initiated a graceful disconnect uses the WSAEventSelect function as follows :

Call WSAEventSelect to register for FD_CLOSE notification. Call shutdown with how=SD_SEND. When FD_CLOSE received, call the recv or WSARecv until the function completes with success and indicates that zero bytes were received. If SOCKET_ERROR is returned, then the graceful disconnect is not possible. Call closesocket.

Another method to wait for notification that the remote end has sent all its data and initiated a graceful disconnect uses overlapped receive calls follows :

Call shutdown with how=SD_SEND. Call recv or WSARecv until the function completes with success and indicates zero bytes were received. If SOCKET_ERROR is returned, then the graceful disconnect is not possible. Call closesocket.

For more information, see the section on 07001.

换句话说,至少对于TCP,调用shutdown(SD_SEND)会通知对等方您已完成发送更多数据,并且很可能很快就会关闭您的连接.同样,同伴也会为你做同样的礼貌.这样,两个对等体都可以知道连接在两端都是有意关闭的.这被称为优雅断开连接,而不是中断或异常断开连接.

默认情况下,如果不调用shutdown(SD_SEND),closesocket()将尝试为您执行正常关闭,除非禁用套接字linger选项.最好不要依赖这种行为,你应该在调用closesocket()之前自己调用shutdown(),除非你有充分的理由不这样做.

点击查看更多相关文章

转载注明原文:c – 为什么我应该在关闭套接字之前使用shutdown()? - 乐贴网