问题描述:
用UDP通信的时候有这个一个问题,假设有A,B两个进程,B向先A发消息,A收到消息以后,开2个线程,一个向B发消息,一个从B收消息,此时如果关掉B进程,A的接收线程就会不阻塞,错误码为10054。
原因:
看了很多资料,原来是winsock的bug,具体原因是:http://support.microsoft.com/kb/263823/
If sending a datagram using the sendto function results in an "ICMP port unreachable" response and the select function is set for readfds, the program returns 1 and the subsequent call to the recvfrom function does not work with a WSAECONNRESET (10054) error response. In Microsoft Windows NT 4.0, this situation causes the select function to block or time out.
解决:
A进程在创建SOCKET后,加入如下的代码:
DWORD dwBytesReturned = 0;
BOOL bNewBehavior = FALSE;
DWORD status;
#define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
// disable new behavior using
// IOCTL: SIO_UDP_CONNRESET
status = WSAIoctl(m_ClientSocket, SIO_UDP_CONNRESET,
&bNewBehavior, sizeof(bNewBehavior),
NULL, 0, &dwBytesReturned,
NULL, NULL);
if (SOCKET_ERROR == status)
{
DWORD dwErr = WSAGetLastError();
if (WSAEWOULDBLOCK == dwErr)
{
// nothing to do
return(FALSE);
}
else
{
printf("WSAIoctl(SIO_UDP_CONNRESET) Error: %d\\n", dwErr);
return(FALSE);
}
}