非阻塞模式下,建立连接没有调用send()和recv()进行数据交互的情况怎么判断服务端连接主动断开?
通过recv()函数,没有数据时返回-1,服务端断开返回0,通过返回0判断服务端是否断开
unsigned long u32NonBlock = 1;
if ( ioctlsocket(pDlg->m_s32Socket, FIONBIO, &u32NonBlock) ) // 非阻塞
{
closesocket(pDlg->m_s32Socket);
pDlg->m_s32Socket = -1;
continue;
}
CHAR sTemBuf[2] = {0};
INT s32Ret = recv(pDlg->m_s32Socket,sTemBuf, sizeof(sTemBuf), 0);
if (0 == s32Ret) // 判断服务器是否主动断开 断开返回0
{
closesocket(pDlg->m_s32Socket);
pDlg->m_s32Socket = -1;
}
u32NonBlock = 0;
if ( ioctlsocket(pDlg->m_s32Socket, FIONBIO, &u32NonBlock) ) // 阻塞
{
closesocket(pDlg->m_s32Socket);
pDlg->m_s32Socket = -1;
continue;
}
时间: 2024-10-13 16:22:33