int error = 0;
sockaddr_in addr_in;
addr_in.sin_family = AF_INET;
addr_in.sin_port = htons(15000);
addr_in.sin_addr.s_addr = INADDR_ANY;
error= ::bind(server,(sockaddr*)&addr_in,sizeof(sockaddr_in));
if(error == SOCKET_ERROR){
cout<<"绑定端口失败!,错误代码:"<<WSAGetLastError()<<endl;
return ;
}
listen(server,5);
if(error == SOCKET_ERROR){
cout<<"监听失败!,错误代码:"<<WSAGetLastError()<<endl;
return ;
}
cout<<"成功监听端口 :"<<ntohs(addr_in.sin_port)<<endl;
WSAEVENT eventArray[WSA_MAXIMUM_WAIT_EVENTS]; // 事件对象数组
SOCKET sockArray[WSA_MAXIMUM_WAIT_EVENTS]; // 事件对象数组对应的SOCKET句柄
int nEvent = 0; // 事件对象数组的数量
WSAEVENT event0 = ::WSACreateEvent();
::WSAEventSelect(server,event0,FD_ACCEPT|FD_CLOSE);
eventArray[nEvent]=event0;
sockArray[nEvent]=server;
nEvent++;
while(true){
int nIndex = ::WSAWaitForMultipleEvents(nEvent,eventArray,false,WSA_INFINITE,false);
if( nIndex == WSA_WAIT_IO_COMPLETION || nIndex == WSA_WAIT_TIMEOUT ){
cout<<"等待时发生错误!错误代码:"<<WSAGetLastError()<<endl;
break;
}
nIndex = nIndex - WSA_WAIT_EVENT_0;
WSANETWORKEVENTS event;
SOCKET sock = sockArray[nIndex];
::WSAEnumNetworkEvents(sock,eventArray[nIndex],&event);
if(event.lNetworkEvents & FD_ACCEPT){
if(event.iErrorCode[FD_ACCEPT_BIT]==0){
if(nEvent >= WSA_MAXIMUM_WAIT_EVENTS){
cout<<"事件对象太多,拒绝连接"<<endl;
continue;
}
sockaddr_in addr;
int len = sizeof(sockaddr_in);
SOCKET client = ::accept(sock,(sockaddr*)&addr,&len);
if(client!= INVALID_SOCKET){
cout<<"接受了一个客户端连接 "<<inet_ntoa(addr.sin_addr)<<":"<<ntohs(addr.sin_port)<<endl;
WSAEVENT eventNew = ::WSACreateEvent();
::WSAEventSelect(client,eventNew,FD_READ|FD_CLOSE|FD_WRITE);
eventArray[nEvent]=eventNew;
sockArray[nEvent]=client;
nEvent++;
}
}
}else if(event.lNetworkEvents & FD_READ){
if(event.iErrorCode[FD_READ_BIT]==0){
char buf[2500];
ZeroMemory(buf,2500);
int nRecv = ::recv( sock,buf,2500,0);
if(nRecv>0){
cout<<"收到一个消息 :"<<buf<<endl;
char strSend[] = "I recvived your message.";
::send(sock,strSend,strlen(strSend),0);
}
}
}else if(event.lNetworkEvents & FD_CLOSE){
::WSACloseEvent(eventArray[nIndex]);
::closesocket(sockArray[nIndex]);
cout<<"一个客户端连接已经断开了连接"<<endl;
for(int j=nIndex;j<nEvent-1;j++){
eventArray[j]=eventArray[j+1];
sockArray[j]=sockArray[j+1];
}
nEvent--;
} else if(event.lNetworkEvents & FD_WRITE ){
cout<<"一个客户端连接允许写入数据"<<endl;
}
} // end while
::closesocket(server);
}