
在这个MSDN页面上:
Sending and Receiving Data on the Client
它建议使用以下方法关闭套接字的发送方:
shutdown(SOCK_ID, SD_SEND);
我为什么要?
也许我没有,它只是一个推荐?也许是为了节省记忆?也许速度?
有没有人有想法?
shutdown()文档中:
If the how parameter is
SD_SEND, subsequent calls to thesendfunction are disallowed. For TCP sockets, aFINwill 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
Callshutdownto close connection before callingclosesocket. One method to wait for notification that the remote end has sent all its data and initiated a graceful disconnect uses theWSAEventSelectfunction as follows :WSAEventSelectto register forFD_CLOSEnotification. Callshutdownwithhow=SD_SEND. WhenFD_CLOSEreceived, call therecvorWSARecvuntil the function completes with success and indicates that zero bytes were received. IfSOCKET_ERRORis returned, then the graceful disconnect is not possible. Callclosesocket.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 :
Callshutdownwithhow=SD_SEND. CallrecvorWSARecvuntil the function completes with success and indicates zero bytes were received. IfSOCKET_ERRORis returned, then the graceful disconnect is not possible. Callclosesocket.…
For more information, see the section on 07001.
换句话说,至少对于TCP,调用shutdown(SD_SEND)会通知对等方您已完成发送更多数据,并且很可能很快就会关闭您的连接.同样,同伴也会为你做同样的礼貌.这样,两个对等体都可以知道连接在两端都是有意关闭的.这被称为优雅断开连接,而不是中断或异常断开连接.
默认情况下,如果不调用shutdown(SD_SEND),closesocket()将尝试为您执行正常关闭,除非禁用套接字linger选项.最好不要依赖这种行为,你应该在调用closesocket()之前自己调用shutdown(),除非你有充分的理由不这样做.
转载注明原文:c – 为什么我应该在关闭套接字之前使用shutdown()? - 乐贴网