求助WSAEventSelect
#include"D:/WSacode/commonHeader/SockInitClass.h"
#include<time.h>
#ifndef UNICODE
#define UNICODE
#endif
SockInitClass SockInit;
using namespace std;
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,PSTR pszCmdLine,int nShowCmd)
//int main()
{
WSAEVENT eventArray[WSA_MAXIMUM_WAIT_EVENTS];
SOCKET sockArray[WSA_MAXIMUM_WAIT_EVENTS];
int nEventTotal=0;
SOCKET sListen=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
sockaddr_in sin;
int Port=5150;
sin.sin_family=AF_INET;
sin.sin_port=htons(Port);
sin.sin_addr.s_addr=INADDR_ANY;
if(bind(sListen,(SOCKADDR*)&sin,sizeof(sin))==SOCKET_ERROR)
{
//cout<<"bind failed"<<WSAGetLastError()<<endl;
MessageBox(NULL,TEXT("bind() failed"),TEXT("test"),0);
closesocket(sListen);
return 0;
}
listen(sListen,5);
WSAEVENT event=WSACreateEvent();
WSAEventSelect(sListen,event,FD_ACCEPT|FD_CLOSE|FD_READ);
eventArray[nEventTotal]=event;
sockArray[nEventTotal]=sListen;
++nEventTotal;
while(true)
{
int nIndex=WSAWaitForMultipleEvents(nEventTotal,eventArray,false,WSA_INFINITE,false);
nIndex=nIndex-WSA_WAIT_EVENT_0;
for(int i=nIndex;i<nEventTotal;++i)
{
static int sequence=0;
nIndex=WSAWaitForMultipleEvents(1,&eventArray[i],true,1000,false);
if(nIndex==WSA_WAIT_FAILED||nIndex==WSA_WAIT_TIMEOUT)
{
continue;
}
else
{
WSANETWORKEVENTS event;
WSAEnumNetworkEvents(sockArray[i],eventArray[i],&event);
if(event.lNetworkEvents&FD_ACCEPT) //new connection request
{
if(event.iErrorCode[FD_ACCEPT_BIT]==0)
{
if(nEventTotal>WSA_MAXIMUM_WAIT_EVENTS)
{
//cout<<"too many connections"<<endl;
MessageBox(NULL,TEXT("too many connections!"),TEXT("test"),0);
continue;
}
//cout<<"FD_ACCEPT"<<endl;
MessageBox(NULL,TEXT("FD_ACCEPT"),TEXT("test"),0);
SOCKET sNew=accept(sockArray[i],NULL,NULL); //accept the request
WSAEVENT event=WSACreateEvent();
WSAEventSelect(sNew,event,FD_ACCEPT|FD_CLOSE|FD_READ);
eventArray[nEventTotal]=event; //add the new event to the event array
sockArray[nEventTotal]=sNew; //add the new socket to the socket array
nEventTotal+=2;
}
}
else if(event.lNetworkEvents&FD_CLOSE)
{
if(event.iErrorCode[FD_CLOSE_BIT]==0)
{
//cout<<"FD_CLOSE"<<endl;
MessageBox(NULL,TEXT("FD_CLOSE"),TEXT("test"),0);
closesocket(sockArray[i]);
for(int j=i;j<nEventTotal-1;++j)
{
sockArray[j]=sockArray[j+1];
eventArray[j]=eventArray[j+1];
}
--nEventTotal;
}
}
else if(event.lNetworkEvents&FD_READ)
{
if(event.iErrorCode[FD_READ_BIT]==0)
{
//cout<<"FD_READ"<<endl;
MessageBox(NULL,TEXT("FD_READ"),TEXT("test"),0);
char szText[1024];
int iResult=recv(sockArray[i],szText,sizeof(szText),0);
if(iResult>0)
{
// cout<<"Message received: "<<szText<<endl;
MessageBox(NULL,TEXT("message received"),TEXT("test"),0);
}
}
}
}
// cout<<"sequence: "<<++sequence<<" \nDelay 2 seconds"<<endl;
}
}
return 0;
}
请各位看看,这里FD_CLOSE,FD_READ_FD_ACCEPT,其中FD_READ没有出现,FD_ACCEPT,FD_CLOSE都出现了,但我吧FD_CLOSE和FD_READ两个else if语句顺序对调以后,FD_CLOSE没有出现,FD_CLOSE,FD_ACCEPT出现了。而但我把FD_ACCEPT放到最后,三者都可以显示。这究竟是什么原因呢? 网络编程 windows
[解决办法]
是不是因为event.lNetworkEvents这个条件的问题啊??