WSAEventSelect模型示例

#include "CInitSocket.h"
#include
<iostream>
using namespace std;

CInitSock initsocket;
int main()
{
//时间句柄和套接字句柄数组
WSAEVENT eventArrary[WSA_MAXIMUM_WAIT_EVENTS];
SOCKET sockArray[WSA_MAXIMUM_WAIT_EVENTS];

int nEventTotal=0; //事件总数
USHORT nPort=4567;
SOCKET ListenSocket
=socket(AF_INET,SOCK_STREAM,0);
sockaddr_in addrin;
addrin.sin_addr.S_un.S_addr
=htonl(INADDR_ANY);
addrin.sin_family
=AF_INET;
addrin.sin_port
=htons(nPort);
if (SOCKET_ERROR==bind(ListenSocket,(LPSOCKADDR)&addrin,sizeof(addrin)))
{
cout
<<"套接字绑定失败!\n";
return -1;
}
listen(ListenSocket,
5);

//创建事件对象,并与新的套接字关联
WSAEVENT hEvent=WSACreateEvent();
WSAEventSelect(ListenSocket,hEvent,FD_ACCEPT
| FD_CLOSE);
//添加到数组中
eventArrary[nEventTotal]=hEvent;
sockArray[nEventTotal]
=ListenSocket;
nEventTotal
++;
//处理网络事件
while(true)
{
//在所有事件对象上等待,由于第三个茶参数是FALSE,所以返回值指向第一个有事件发生的套接字
int nIndex=WSAWaitForMultipleEvents(nEventTotal,eventArrary,FALSE,WSA_INFINITE,FALSE);
// 对每个事件调用WSAWaitForMultipleEvents,确定其状态
nIndex=nIndex-WSA_WAIT_EVENT_0;
for (int i=nIndex;i<nEventTotal;i++)
{
nIndex
=WSAWaitForMultipleEvents(1,&eventArrary[i],TRUE,1000,FALSE);
if (nIndex==WSA_WAIT_FAILED || nIndex==WSA_WAIT_TIMEOUT)
{
continue;
}
else
{
//获取到来的通知消息,WSAEnumNetworkEvents会自动重置受信事件
WSANETWORKEVENTS event;
WSAEnumNetworkEvents(sockArray[i],eventArrary[i],
&event);
if (event.lNetworkEvents & FD_ACCEPT)
{
if (event.iErrorCode[FD_ACCEPT_BIT]==0)
{
if (nEventTotal>WSA_MAXIMUM_WAIT_EVENTS)
{
cout
<<"Too much connections!\n";
continue;
}
SOCKET NewSocket
=accept(sockArray[i],NULL,NULL);
WSAEVENT NewEvent
=WSACreateEvent();
WSAEventSelect(NewSocket,NewEvent,FD_READ
| FD_WRITE | FD_CLOSE);
eventArrary[nEventTotal]
=NewEvent;
sockArray[nEventTotal]
=NewSocket;
nEventTotal
++;
}
}
else if (event.lNetworkEvents & FD_READ)
{
if (event.iErrorCode[FD_READ_BIT]==0)
{
char szText[256];
int nRecv=recv(sockArray[i],szText,256,0);
if (nRecv>0)
{
szText[nRecv]
='\0';
cout
<<"接收到数据"<<szText<<endl;
}
}
}
else if (event.lNetworkEvents & FD_WRITE)
{
if (event.iErrorCode[FD_WRITE_BIT]==0)
{
//do something
}
}
else if (event.lNetworkEvents & FD_CLOSE)
{
if (event.iErrorCode[FD_CLOSE_BIT]==0)
{
closesocket(sockArray[i]);
for (int j=i;j<nEventTotal;j++)
{
//从数组中删除
sockArray[j]=sockArray[j+1];
eventArrary[j]
=eventArrary[j+1];
}
}
}
}
}

}
return 0;
}
posted @ 2011-07-08 09:31  likebeta  阅读(803)  评论(0编辑  收藏  举报