基于IOCP的服务器中使用TCP连接时如何知道客户端已经异常断开?


基于IOCP的服务器,经常会发生客户端断开连接。由于网络经常出现一些异常情况,比如一方的机器突然断电,这时要过很久后才能得知该TCP链接已经断掉。如何才能很快知道该TCP链接已经断了?

网络编程 windows

pluto 12 years, 9 months ago
   
  BOOL r = ::GetQueuedCompletionStatus(hCompletionPort,      &dwBytesTransferred, (LPDWORD)&hCompletionSocket, (LPWSAOVERLAPPED *) &lpOvlpEx, INFINITE);
  
if (hCompletionSocket== INVALID_SOCKET || lpOvlpEx == NULL)
{
Sleep(10);
continue;
}

if (!r)
{
proxy->SafeClose(lpOvlpEx);
TRACE("GetQueuedCompletionStatus error! %d\n",hSocket);
continue;
}
else if (dwBytesTransferred ==0)
{
proxy->SafeClose(lpOvlpEx);
TRACE(".....................%d..........closed & freed........\n",hSocket);
continue;
}
}

上面的GetQueuedCompletionStatus是接收IOCP通知的主要函数,通过dwBytesTransferred、hCompletionSocket、lpOvlpEx以及返回值r即可判断出客户端是否关闭。

stoomy answered 12 years, 9 months ago

Your Answer