1.使用步骤
1) 创建一个newSock。
2) newEvent = WSACreateEvent() 创建个event
3) WSAEventSelect(newSock,newEvent,lNetworkEvents) 把 newSock,newEvent 关联起来。lNetworkEvents可以为 FD_ACCEPT ,FD_READ ,FD_WRITE,FD_CLOSE 等等.
4) Index = WSAWaitForMultipleEvents(EventTotal,EventArray,FAlSE,100/*WSA_INFINITE*/,FALSE) 等待事件句柄。
5) int WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEventObject,LPWSANETWORKEVENTS lpNetworkEvents);调查发生什么类型网络事件。
6) 用lpNetworkEvents.lNetworkEvents & FD_ACCEPT ,lpNetworkEvents.lNetworkEvents & FD_CLOSE找到各个事件处理。
2.问题
1)当客服端关闭时,响应FD_CLOSE事件,lpNetworkEvents.iErrorCode值为10053 ?
首先确定缓存中是否还有数据没处理。
然后确信客服端关闭是函数调用(shutdown->closesocket->WSACleanup)
2)WSAWaitForMultipleEvents调用后如何将相应的工作状态转为未传信状态 ?
可以调用WSAResetEvent();
还可以把相应的event传给WSAEnumNetworkEvents第2个参数,效果和WSAResetEven一样。
3.注意点
1) 当WSACloseEvent后,要记得把EventTotal减1;
2) WSAWaitForMultipleEvents每次只能处理64个Event,如要处理超过64个event 这有个办法
DWORD My_WSAWaitForMultipleEvents(
DWORD cEvents,
const WSAEVENT FAR *lphEvents,
BOOL fWaitAll,
DWORD dwTimeout,
BOOL fAlertable
)
{
if(cEvents <= WSA_MAXIMUM_WAIT_EVENTS)
{
return WSAWaitForMultipleEvents(cEvents,lphEvents,fWaitAll,dwTimeout,fAlertable);
}
else if(cEvents>WSA_MAXIMUM_WAIT_EVENTS)
{
int eventNum = WSA_MAXIMUM_WAIT_EVENTS;
int evenStart = 0;
DWORD Index;
while( eventNum > 0 )
{
Index = WSAWaitForMultipleEvents(eventNum,lphEvents+evenStart,fWaitAll,dwTimeout,fAlertable);
if(WSA_WAIT_TIMEOUT == Index)
{
evenStart += eventNum;
if((evenStart + WSA_MAXIMUM_WAIT_EVENTS) > cEvents)
{
eventNum = cEvents - evenStart;
}
continue;
}
break;
}
return index;
}
}