MSDN:Note To assure that all data is sent and received on a connection, an application should call shutdown before calling closesocket (see Graceful shutdown, linger options, and socket closure for more information). Also note, an FD_CLOSE network event is not posted after closesocket is called. Here is a summary of closesocket behavior: If the l_onoff member of the LINGER structure is zero (the default for a socket), closesocket returns immediately and the connection is gracefully closed in the background. If the l_onoff member of the linger structure is set to non-zero and the l_linger member is set to zero (no timeout) closesocket returns immediately and the connection is reset or terminated. If the l_onoff member of the linger structure is set to non-zero and the l_linger member is set to a non-zero timeout: – For a blocking socket, closesocket blocks until all data is sent or the timeout expires.– For a nonblocking socket, closesocket returns immediately indicating failure.
struct linger
{
u_short l_onoff;
u_short l_linger;
};
linger m_sLinger;
m_sLinger.l_onoff = 1; //在调用closesocket()时还有数据未发送完,允许等待
// 若m_sLinger.l_onoff=0;则调用closesocket()后强制关闭
m_sLinger.l_linger = 5; //设置等待时间为5秒
setsockopt( s, SOL_SOCKET, SO_LINGER, ( const char* )&m_sLinger, sizeof( linger ) );
Here is a summary of closesocket behavior:
If the l_onoff member of the LINGER structure is zero (the default for a socket), closesocket returns immediately and the connection is gracefully closed in the background.
If the l_onoff member of the linger structure is set to non-zero and the l_linger member is set to zero (no timeout) closesocket returns immediately and the connection is reset or terminated.
If the l_onoff member of the linger structure is set to non-zero and the l_linger member is set to a non-zero timeout:
– For a blocking socket, closesocket blocks until all data is sent or the timeout expires.– For a nonblocking socket, closesocket returns immediately indicating failure.
(这是我找到的帖子,里面3楼是这么说的)